Parallelizing a Sliding Dot-Product Filter Across CPU Cores
System DesignModel answerLast updated
Design a multithreaded CPU routine for valid 1D correlation that adapts to tiny, huge, and thread-capped cases, covering partitioning, false sharing, SIMD, and merging.
You are asked to build a CPU-parallel routine that computes a valid 1D sliding dot product (the "valid" form of convolution as used in signal processing and ML, with no kernel flip).
Given an input array x of length N and a filter h of length K, the output y has length M = N − K + 1, and
y[i] = Σ_{j=0}^{K−1} x[i+j] · h[j], for 0 ≤ i < M.
Every output element is an independent dot product of length K.
Describe your design, with code or pseudocode, for each of these scenarios:
N = 1,000,000andK = 3.N = 1,000,000andK = 1,000,000.- At most 100 worker threads may be used. Give a single configurable policy, reusable for scenarios 1 and 2, that caps the worker count and picks chunk sizes accordingly.
Your answer should explain:
- how the work is partitioned and assigned to threads, and how load is balanced;
- how partial results are combined, and what synchronization is required;
- how you keep cache use efficient and avoid false sharing;
- how you apply SIMD vectorization;
- how you choose chunk/tile sizes and the number of threads.
Finish with an API-level design or pseudocode for the unified routine that handles all three scenarios.
Hints
Hint 1
Count the total work as M·K and look at M in each scenario. When M is about a million, you can split by output; when M is 1, splitting by output gives no parallelism at all.
Hint 2
Think of the computation as a 2D grid of (output index, tap index). Cutting along the output axis yields disjoint writes, while cutting along the tap axis yields private partial sums that need a deterministic merge.
Hint 3
Threads beyond the core count (and beyond the point where memory bandwidth saturates) do not help. Derive the thread count from total work, a minimum useful work per task, the hardware core count, and the cap of 100.
Hint 4
Align output-block boundaries to cache lines so neighbors never write the same line, and keep partial sums in thread-local accumulators written once.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing
- Output length is
M = N − K + 1and total work isW = M·Kmultiply-adds. This number drives the design. - Scenario 1 (N = 10⁶, K = 3): M ≈ 10⁶ independent outputs, W ≈ 3·10⁶. Each loaded element yields only about 3 FLOPs, so the job is memory-bandwidth bound.
- Scenario 2 (N = K = 10⁶): M = 1. The whole job is one dot product of length 10⁶. Output-splitting yields zero parallelism, so we must split the reduction over taps.
- Clarifications worth asking: element type (assume float64), whether results must be bit-reproducible, and whether oversubscription is allowed.
- FFT-based convolution only pays off when both M and K are large. Here direct evaluation is already optimal: O(N) and O(K) work.
Core idea: a 2D iteration space with two parallel axes
Treat the problem as the grid i ∈ [0, M) by j ∈ [0, K) and cut it into tiles (output block, tap block).
- Output-axis cuts: tiles write disjoint slices of
y, so no synchronization is needed beyond the final join. Each block reads its own range ofxplus aK−1halo that is shared read-only with its neighbor. - Tap-axis cuts: each tile produces a private partial vector for its output block. Partials are summed after the join in a fixed order.
The policy decides how many cuts per axis:
- Scenario 1: many output blocks, one tap block (pure data parallelism).
- Scenario 2: one output block, many tap blocks (parallel reduction plus merge).
- Mixed shapes (for example M = 100, K = 10⁶): cut both.
Correctness and determinism
A sum splits over disjoint tap ranges because addition is associative in exact arithmetic. In floating point the rounding changes slightly, so use a fixed partition and a fixed merge order. The result is then deterministic for a given configuration. Output tiles are disjoint and inputs are read-only, so there are no data races.
Thread-count and chunk policy (scenario 3)
Let T_max = 100 and let MIN_WORK ≈ 2¹⁸ multiply-adds, the smallest task worth scheduling (keeps ~10 µs of thread overhead under about 1%).
T = min(T_max, hardware_cores, max(1, W // MIN_WORK))
- Do not exceed physical cores. 100 threads on 16 cores only adds context switches and cache thrashing. Memory-bound loops saturate bandwidth at roughly 8–16 threads anyway, so the cap of 100 is a ceiling, not a target.
- Load balancing. Create about
4·Ttasks and distribute them dynamically from a shared queue. Tiles cost the same in theory, but OS noise, NUMA, and frequency effects make real runtimes uneven. Several tasks per thread absorb that variance. - False sharing. Round output-block boundaries to a multiple of 16 float64 (128 B), so neighbors never write the same cache line of
y. Keep reduction partials in thread-local accumulators written once. If a shared array of per-thread partials is unavoidable, pad each slot to 64 B. - Tile size and locality. A tile touches
B + Kt − 1elements ofxandKtofh. PickBandKtso that working set fits in L2 (about 256 KB to 1 MB per core). In scenario 1,hlives in registers andxstreams once, which the hardware prefetcher handles. In scenario 2, each thread streams its own 1/T slice of two 8 MB arrays once.
SIMD
Vectorize along the longer dimension of the tile.
- Many outputs, few taps: loop over taps outermost and outputs innermost,
acc[i0:i1] += h[j] * x[i0+j : i1+j]. This is a contiguous AXPY that maps to FMA. For K = 3, broadcast the taps into registers and unroll fully. - Few outputs, many taps: compute a contiguous dot product per output, using several independent SIMD accumulators (for example 4) to hide FMA latency, then reduce horizontally at the end.
Reference implementation (Python/NumPy)
NumPy releases the GIL in vector kernels, so a thread pool gives real parallelism on large slices. In C++ the same structure maps onto OpenMP or std::thread with intrinsics inside the tile kernels.
import os, math
import numpy as np
from concurrent.futures import ThreadPoolExecutor
ALIGN = 16; MIN_WORK = 1 << 18; MIN_OUT = 4096; MIN_TAPS = 8192
def bounds(n, parts, align=1):
step = math.ceil(n / max(1, parts))
step = max(align, math.ceil(step / align) * align)
return [(s, min(s + step, n)) for s in range(0, n, step)]
def tile(x, h, i0, i1, j0, j1):
nb, kt = i1 - i0, j1 - j0
if nb >= kt: # AXPY over outputs
acc = np.zeros(nb)
for j in range(j0, j1):
acc += h[j] * x[i0 + j:i1 + j]
return acc
hs = h[j0:j1] # dot product per output
return np.array([np.dot(x[i + j0:i + j1], hs) for i in range(i0, i1)])
def conv_valid(x, h, max_threads=100):
x = np.ascontiguousarray(x, dtype=np.float64)
h = np.ascontiguousarray(h, dtype=np.float64)
N, K = len(x), len(h)
if K == 0 or K > N:
return np.zeros(0)
M = N - K + 1
T = min(max_threads, os.cpu_count() or 1, max(1, M * K // MIN_WORK))
if T == 1:
return tile(x, h, 0, M, 0, K)
tasks = 4 * T
mo = max(1, min(tasks, M // MIN_OUT))
kp = max(1, min(math.ceil(tasks / mo), K // MIN_TAPS))
ob, tb = bounds(M, mo, ALIGN), bounds(K, kp)
y = np.empty(M)
with ThreadPoolExecutor(max_workers=T) as pool:
f = {(a, b): pool.submit(tile, x, h, i0, i1, j0, j1)
for a, (i0, i1) in enumerate(ob) for b, (j0, j1) in enumerate(tb)}
for a, (i0, i1) in enumerate(ob):
acc = f[(a, 0)].result()
for b in range(1, len(tb)): # fixed merge order
acc = acc + f[(a, b)].result()
y[i0:i1] = acc
return y
How the policy plays out
- Scenario 1: W ≈ 3·10⁶, so T ≈ 11 on a large machine (limited by MIN_WORK, not by the cap). Output blocks are many and aligned, one tap block, no merge, and each thread streams its slice of
xonce. - Scenario 2: M = 1, so there is a single output block and the policy yields many tap blocks. Each thread computes a partial dot product over its slice, and the main thread adds the few partials in fixed order. The merge cost is trivial relative to 10⁶ multiply-adds.
- Scenario 3: the cap of 100 only binds when W is huge and there are enough cores. Even then T is clamped to the core count, and extra parallelism comes from having more tasks than threads, not more threads.
Trade-offs and common mistakes
- Splitting only by output makes scenario 2 run on one core.
- Spawning one thread per output (or per tap) drowns the work in overhead.
- Having threads increment adjacent slots of a shared partial array causes false sharing; accumulate locally and write once.
- Using 100 threads on a few cores hurts memory-bound work.
- Forgetting that tap-splitting changes floating-point rounding. Document it, and fix partition and merge order if reproducibility matters.
- For both K and M large (say 10⁵ each), consider FFT or overlap-add, which beats direct O(M·K).
- A tree-reduction merge helps only when the number of partials is large. For tens of partials a sequential merge is simpler and deterministic.