KatInterview

Parallelizing a Sliding Dot-Product Filter Across CPU Cores

System DesignModel answer
HardModel answerSystem Designmultithreadingparallel-reductionfalse-sharing

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

  1. N = 1,000,000 and K = 3.
  2. N = 1,000,000 and K = 1,000,000.
  3. 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.