Skip to content

Commit da15a97

Browse files
ElektrikAkarclaude
andcommitted
feat(metal): 1-vs-N / K-vs-N kernels + fix pre-existing band-edge bug
Adds dtw_kvn_wavefront and dtw_kvn_wavefront_global MSL kernels plus four host-side entry points mirroring the CUDA K-vs-N API: compute_dtw_one_vs_all_metal(series, query_index, opts) compute_dtw_one_vs_all_metal(query, targets, opts) compute_dtw_k_vs_all_metal(series, query_indices, opts) compute_dtw_k_vs_all_metal(queries, targets, opts) Enables GPU-accelerated k-medoids cluster-assignment on Apple Silicon (K*N pairs per iteration instead of precomputing N*N). Kernel params are packed into a struct bound as a single constant buffer; pair decoding uses divmod over (K, N) instead of upper-triangle enumeration. Bug fix (affects ALL four wavefront kernels — dtw_wavefront, dtw_wavefront_global, dtw_kvn_wavefront, dtw_kvn_wavefront_global): the band-range iteration optimization assumed out-of-band cells in the rotating scratch buffers retain INF from initialization. That is false: the 3-buffer rotation reuses each buffer as 'cur' every 3 diagonals, so cells outside the current band can hold real DTW values from 3 diagonals ago. When the band range shifts by 1 between diagonals (always happens on odd-parity k+band transitions), the new band edge reads stale data and produces distances SMALLER than the true banded DTW. Pre-existing NxN wavefront banded paths silently returned wrong answers — the existing test suite never cross-checked banded Metal against CPU dtwBanded. For the specific seeds we had, the error was 0.12% (random chance that stale cells weren't on the DP path). For different data the error can exceed 7%: cpu_banded=680.17 vs gpu_band=633.06 at 75x10000 band=20. Uncovered by a new K-vs-N banded test. Fix: after each diagonal's in-band writes, stamp INF into the two band-adjacent positions (i_lo-1 and i_hi+1). Two extra writes per diagonal per pair. Performance impact on wavefront banded workloads: 0-9% slower (75x2500 band=250: 212 -> 232 ms; 75x10000 band=1000: 2010 -> 2083 ms). Tight-band 75x10000 band=100 is unaffected because it uses the row-major dtw_banded_row kernel. Tests: test_metal_correctness.cpp grows from 9 cases / 91 assertions to 14 cases / 149 assertions — adds an NxN-wavefront-banded vs CPU dtwBanded cross-check and four K-vs-N cases (1-vs-N by index, 1-vs-N external query, K-vs-N unbanded by indices, K-vs-N banded external). Full ctest suite: 69/69 pass. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 6db6621 commit da15a97

4 files changed

Lines changed: 764 additions & 46 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,9 @@ This changelog contains a non-exhaustive list of new features and notable bug-fi
3434
- `dtw_wavefront_global` (device memory): scratch lives in unified GPU memory; any max_L supported.
3535
- `dtw_banded_row` (tight-band row-major): one thread per pair, no intra-threadgroup barriers, coalesced device-memory scratch with register-rotated prev/cur window. Fires when `band > 0 AND band * 20 < max_L AND band ≤ 512` — the regime where anti-diagonal barrier overhead dominates the wavefront kernel. On 75 × 10000 band=100: **1.01 s vs 1.40 s for wavefront (1.4×) and 1.76 s for CPU (1.7×)**. Dispatcher picks automatically; `MetalDistMatResult::kernel_used` reports which kernel ran.
3636
- **macOS GPU-watchdog avoidance**: long dispatches (>~2 s per command buffer) fail with `kIOGPUCommandBufferCallbackErrorImpactingInteractivity`. The dispatcher now chunks pairs across multiple command buffers (budget ≈ 5 × 10⁹ cells per buffer) so arbitrary N × L workloads complete without triggering the watchdog.
37-
- **Tests**: `test_metal_correctness.cpp` (9 cases, 91 assertions) validates GPU output against CPU reference at FP32 tolerance, covers length-2000, the 10 000-length global-memory fallback, and three banded-row dispatch scenarios (tight-band hit, long-series tight-band, wide-band routing back to wavefront). `test_metal_mmap.cpp` exercises the Metal strategy through `Problem::fillDistanceMatrix` into both `DenseDistanceMatrix` and the memory-mapped distance-matrix paths.
37+
- **K-vs-N Metal kernels** (`dtw_kvn_wavefront`, `dtw_kvn_wavefront_global`): K queries × N targets parallel DTW on GPU, mirroring the CUDA `compute_dtw_k_vs_all` API. New host functions `compute_dtw_k_vs_all_metal` (two overloads: by-indices-into-series, and separate queries + targets) and `compute_dtw_one_vs_all_metal` (two overloads: by index, and external query). Result types `MetalKVsNResult` / `MetalOneVsNResult` match the CUDA shape. Enables GPU-accelerated k-medoids cluster-assignment loops on Apple Silicon — K*N pairs (instead of precomputing N² for small-K workloads).
38+
- **Band-edge correctness fix** (affects all four wavefront kernels — `dtw_wavefront`, `dtw_wavefront_global`, `dtw_kvn_wavefront`, `dtw_kvn_wavefront_global`): the band-range iteration optimization relied on "out-of-band cells retain their INF initialization," which was wrong given the 3-buffer rotation — every 3 diagonals each buffer is reused as `cur`, so cells outside the current band can retain real DTW values from 3 diagonals ago. When the band range shifts by ±1 between diagonals, in-band reads at the new band edge hit those stale values and produce distances smaller than the true banded DTW. Pre-existing NxN wavefront banded paths silently returned wrong values (≤0.12% for the random-seed tests we had, up to ~7% on data where the stale values happen to lie on the DP path). Fix: after each diagonal's in-band writes, stamp INF into the two band-adjacent positions (`i_lo-1` and `i_hi+1`). Two extra writes per diagonal per pair; wavefront-banded benchmarks shift 0–9% (e.g. 75×2500 band=250: 212 → 232 ms; 75×10000 band=100 tight-band uses `dtw_banded_row` and is unaffected). Verified against CPU `dtwBanded` by new directed test "Metal wavefront NxN banded matches CPU dtwBanded".
39+
- **Tests**: `test_metal_correctness.cpp` (14 cases, 149 assertions) validates GPU output against CPU reference at FP32 tolerance, covers length-2000, the 10 000-length global-memory fallback, three banded-row dispatch scenarios, an NxN wavefront-banded cross-check against `dtwBanded`, and four K-vs-N cases (1-vs-N by index, 1-vs-N external query, K-vs-N by indices, K-vs-N banded). `test_metal_mmap.cpp` exercises the Metal strategy through `Problem::fillDistanceMatrix` into both `DenseDistanceMatrix` and the memory-mapped distance-matrix paths.
3840
- **Benchmark**: `benchmarks/bench_metal_dtw.cpp` (Google Benchmark) compares Metal vs CPU at matching sizes; JSON lands in `benchmarks/results/mac_m2max/`.
3941

4042
### Added (macOS support)

‎dtwc/metal/metal_dtw.hpp‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,53 @@ MetalDistMatResult compute_distance_matrix_metal(
5858
const std::vector<std::vector<double>> &series,
5959
const MetalDistMatOptions &opts = {});
6060

61+
// ===========================================================================
62+
// 1-vs-N and K-vs-N DTW computation (k-medoids assignment loop).
63+
// ===========================================================================
64+
65+
/// Result of a 1-vs-N DTW computation.
66+
struct MetalOneVsNResult {
67+
std::vector<double> distances; ///< N distances from query to each target.
68+
size_t n = 0; ///< Number of target series.
69+
double gpu_time_sec = 0; ///< GPU kernel execution time.
70+
std::string kernel_used; ///< Which kernel variant ran.
71+
};
72+
73+
/// Compute DTW distances from one series (by index) to all N series.
74+
/// Result: `distances[query_index] == 0`, others are DTW(series[query_index], series[j]).
75+
MetalOneVsNResult compute_dtw_one_vs_all_metal(
76+
const std::vector<std::vector<double>> &series,
77+
size_t query_index,
78+
const MetalDistMatOptions &opts = {});
79+
80+
/// Compute DTW distances from an external query series to all N targets.
81+
MetalOneVsNResult compute_dtw_one_vs_all_metal(
82+
const std::vector<double> &query,
83+
const std::vector<std::vector<double>> &targets,
84+
const MetalDistMatOptions &opts = {});
85+
86+
/// Result of a K-vs-N DTW computation. `distances[k*n + j]` = DTW(queries[k], targets[j]).
87+
struct MetalKVsNResult {
88+
std::vector<double> distances;
89+
size_t k = 0;
90+
size_t n = 0;
91+
double gpu_time_sec = 0;
92+
std::string kernel_used;
93+
};
94+
95+
/// Compute K rows of the NxN matrix in one dispatch.
96+
/// `query_indices[K]` picks which series become the queries; all N series remain targets.
97+
MetalKVsNResult compute_dtw_k_vs_all_metal(
98+
const std::vector<std::vector<double>> &series,
99+
const std::vector<size_t> &query_indices,
100+
const MetalDistMatOptions &opts = {});
101+
102+
/// Compute K rows where the queries are a separate collection (not drawn from targets).
103+
MetalKVsNResult compute_dtw_k_vs_all_metal(
104+
const std::vector<std::vector<double>> &queries,
105+
const std::vector<std::vector<double>> &targets,
106+
const MetalDistMatOptions &opts = {});
107+
61108
} // namespace dtwc::metal
62109

63110
#endif // DTWC_HAS_METAL

0 commit comments

Comments
 (0)