|
| 1 | +import pytest |
| 2 | +import numpy as np |
| 3 | +import scipy.ndimage |
| 4 | +import torch |
| 5 | + |
| 6 | +from whisper.timing import dtw_cpu, dtw_cuda, median_filter |
| 7 | + |
| 8 | + |
| 9 | +sizes = [ |
| 10 | + (10, 20), (32, 16), (123, 1500), (234, 189), |
| 11 | +] |
| 12 | +shapes = [ |
| 13 | + (10,), (1, 15), (4, 5, 345), (6, 12, 240, 512), |
| 14 | +] |
| 15 | + |
| 16 | + |
| 17 | +@pytest.mark.parametrize("N, M", sizes) |
| 18 | +def test_dtw(N: int, M: int): |
| 19 | + steps = np.concatenate([np.zeros(N - 1), np.ones(M - 1)]) |
| 20 | + np.random.shuffle(steps) |
| 21 | + x = np.random.random((N, M)).astype(np.float32) |
| 22 | + |
| 23 | + i, j, k = 0, 0, 0 |
| 24 | + trace = [] |
| 25 | + while True: |
| 26 | + x[i, j] -= 1 |
| 27 | + trace.append((i, j)) |
| 28 | + |
| 29 | + if k == len(steps): |
| 30 | + break |
| 31 | + |
| 32 | + if k + 1 < len(steps) and steps[k] != steps[k + 1]: |
| 33 | + i += 1 |
| 34 | + j += 1 |
| 35 | + k += 2 |
| 36 | + continue |
| 37 | + |
| 38 | + if steps[k] == 0: |
| 39 | + i += 1 |
| 40 | + if steps[k] == 1: |
| 41 | + j += 1 |
| 42 | + k += 1 |
| 43 | + |
| 44 | + trace = np.array(trace).T |
| 45 | + dtw_trace = dtw_cpu(x) |
| 46 | + |
| 47 | + assert np.allclose(trace, dtw_trace) |
| 48 | + |
| 49 | + |
| 50 | +@pytest.mark.requires_cuda |
| 51 | +@pytest.mark.parametrize("N, M", sizes) |
| 52 | +def test_dtw_cuda_equivalence(N: int, M: int): |
| 53 | + x_numpy = np.random.randn(N, M).astype(np.float32) |
| 54 | + x_cuda = torch.from_numpy(x_numpy).cuda() |
| 55 | + |
| 56 | + trace_cpu = dtw_cpu(x_numpy) |
| 57 | + trace_cuda = dtw_cuda(x_cuda) |
| 58 | + |
| 59 | + assert np.allclose(trace_cpu, trace_cuda) |
| 60 | + |
| 61 | + |
| 62 | +@pytest.mark.parametrize("shape", shapes) |
| 63 | +def test_median_filter(shape): |
| 64 | + x = torch.randn(*shape) |
| 65 | + |
| 66 | + for filter_width in [3, 5, 7, 13]: |
| 67 | + filtered = median_filter(x, filter_width) |
| 68 | + |
| 69 | + # using np.pad to reflect-pad, because Scipy's behavior is different near the edges. |
| 70 | + pad_width = filter_width // 2 |
| 71 | + padded_x = np.pad(x, [(0, 0)] * (x.ndim - 1) + [(pad_width, pad_width)], mode="reflect") |
| 72 | + scipy_filtered = scipy.ndimage.median_filter(padded_x, [1] * (x.ndim - 1) + [filter_width]) |
| 73 | + scipy_filtered = scipy_filtered[..., pad_width:-pad_width] |
| 74 | + |
| 75 | + assert np.allclose(filtered, scipy_filtered) |
| 76 | + |
| 77 | + |
| 78 | +@pytest.mark.requires_cuda |
| 79 | +@pytest.mark.parametrize("shape", shapes) |
| 80 | +def test_median_filter_equivalence(shape): |
| 81 | + x = torch.randn(*shape) |
| 82 | + |
| 83 | + for filter_width in [3, 5, 7, 13]: |
| 84 | + filtered_cpu = median_filter(x, filter_width) |
| 85 | + filtered_gpu = median_filter(x.cuda(), filter_width).cpu() |
| 86 | + |
| 87 | + assert np.allclose(filtered_cpu, filtered_gpu) |
0 commit comments