diff --git a/docs/Finding_OverlapAdd_ChunkSize.ipynb b/docs/Finding_OverlapAdd_ChunkSize.ipynb new file mode 100644 index 0000000..079d049 --- /dev/null +++ b/docs/Finding_OverlapAdd_ChunkSize.ipynb @@ -0,0 +1,864 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "id": "1783c97f-64f6-4655-9a49-d8d3632ffd57", + "metadata": {}, + "outputs": [], + "source": [ + "import math\n", + "import numpy as np\n", + "import pandas as pd\n", + "import time\n", + "\n", + "from scipy.fft import next_fast_len\n", + "from scipy.special import lambertw" + ] + }, + { + "cell_type": "markdown", + "id": "f6df0fcb-7084-4cf6-a555-33816b31b7a0", + "metadata": {}, + "source": [ + "# Optimizing Overlap-add" + ] + }, + { + "cell_type": "markdown", + "id": "b4c90a5a-8e9b-411a-83bb-68134cb10cf1", + "metadata": {}, + "source": [ + "The overlap-add algorithm is a divide-and-conquer approach. Instead of computing the convolution between `Q` (of the length `m`) and full `T` (of the length `n`), we split `T` into chunks and then compute the full convolution between `Q` and each chunk of `T`. The full convolution between each chunk and `Q` has the length of `N = len(chunk) + len(Q) - 1`. For a chunk of `T` that start at index `i`, its corresponding full convolution with `Q` contributes to the slice of output in `range(i, i + N)` . To achieve lower time complexity, the full convolution (per chunk) can be computed via circular convolution in frequency domain using Fourier transform. The length of circular convolution is `N`.\n", + "\n", + "The following steps show the overlap-add algorithm:\n", + "\n", + "(1) Input: `Q`, `T`, and `chunk_size`
\n", + "(2) Divide `T` into `ceil(n / chunk_size)` chunks
\n", + "(3) Compute full convolution between each chunk and `Q`, and add its result to the slice of output that has the same start as the chunk and its length is `N = chunk_size + m - 1`
\n", + "\n", + "The purpose of this notebook is to explore the impact of `chunk_size` and find a way to determine its optimal size, or, alternatively, the optimal size of `N=chunk_size + m - 1`" + ] + }, + { + "cell_type": "markdown", + "id": "6aa2a8c3-cc23-4395-941a-ec584ba89878", + "metadata": {}, + "source": [ + "## Chunk's size in Overlap-add" + ] + }, + { + "cell_type": "markdown", + "id": "7f6e2903-33e5-427c-9da3-e9d594c854a5", + "metadata": {}, + "source": [ + "To split `T` into two/more chunks, the `chunk_size` can have any value from `1` to `n-1` (inclusive). However, we avoid setting the `chunk_size` to `1` because that definitely explodes the number of chunks to `n`. The `chunk_size` of `n-1` is most likely outperformed by the `chunk_size` of $\\left\\lceil{n/2}\\right\\rceil$. Both cases result in two chunks but the latter one requires circular convolutions of length $N = \\left\\lceil{n/2}\\right\\rceil + m - 1$ instead of $N = (n-1) + m - 1$. So, it should be computationally less expensive.\n", + "\n", + "* $MIN\\space{}chunk\\_size: 2 \\longrightarrow n\\_chunks = \\left\\lceil{n/2}\\right\\rceil$\n", + "* $MAX\\space{}chunk\\_size: \\left\\lceil{n/2}\\right\\rceil \\longrightarrow n\\_chunks = 2$" + ] + }, + { + "cell_type": "markdown", + "id": "53c6928d-30cc-43b3-8704-2f36eee3f562", + "metadata": {}, + "source": [ + "Accordingly:\n", + "* $MIN\\space{}N = 2 + (m-1)$\n", + "* $MAX\\space{}N = \\left\\lceil{n/2}\\right\\rceil + (m-1)$" + ] + }, + { + "cell_type": "markdown", + "id": "4f2ba5bd-cc33-4f2a-9ac5-cd0d9ea55a01", + "metadata": {}, + "source": [ + "FFT has algorithms for faster computation if `N` has certain set of factors. For the sake of simplicity, we call them \"good\" factors in this notebook, and a \"good\" length is a length with \"good\" factors. Scipy provides the function `next_fast_len(x, real=True)`, which returns the smallest integer number that is not less than `x` and their factors are \"good\"." + ] + }, + { + "cell_type": "markdown", + "id": "137a7c42-a680-4bd7-8ac6-f23725f79052", + "metadata": {}, + "source": [ + "So, we are looking for \"good\" values for N that are between `next_fast_len(m+1, real=True)` and `next_fast_len(ceil(n/2) + m - 1, real=True)`. " + ] + }, + { + "cell_type": "markdown", + "id": "99d79b94-a32a-46a6-bde1-77a6872b107e", + "metadata": {}, + "source": [ + "### Example" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "a9dc3729-09b1-4006-b302-a0fb69237ca2", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " N nchunks\n", + "0 270 274\n", + "1 288 125\n", + "2 300 92\n", + "3 320 64\n", + "4 324 60\n", + "5 360 40\n", + "6 375 35\n", + "7 384 32\n", + "8 400 29\n", + "9 405 28\n", + "10 432 24\n", + "11 450 22\n", + "12 480 19\n", + "13 486 18\n", + "14 500 17\n", + "15 512 16\n", + "16 540 15\n", + "17 576 13\n", + "18 600 12\n", + "19 625 12\n", + "20 640 11\n", + "21 648 11\n", + "22 675 10\n", + "23 720 9\n", + "24 729 9\n", + "25 750 9\n", + "26 768 8\n", + "27 800 8\n", + "28 810 8\n", + "29 864 7\n", + "30 900 7\n", + "31 960 6\n", + "32 972 6\n", + "33 1000 6\n", + "34 1024 6\n", + "35 1080 5\n", + "36 1125 5\n", + "37 1152 5\n", + "38 1200 5\n", + "39 1215 5\n", + "40 1250 5\n", + "41 1280 4\n", + "42 1296 4\n", + "43 1350 4\n", + "44 1440 4\n", + "45 1458 4\n", + "46 1500 4\n", + "47 1536 4\n", + "48 1600 4\n", + "49 1620 4\n", + "50 1728 3\n", + "51 1800 3\n", + "52 1875 3\n", + "53 1920 3\n", + "54 1944 3\n", + "55 2000 3\n", + "56 2025 3\n", + "57 2048 3\n", + "58 2160 3\n", + "59 2187 3\n", + "60 2250 3\n", + "61 2304 2\n" + ] + } + ], + "source": [ + "m = 2**8\n", + "n = 2**12\n", + "\n", + "N_lower_bound = next_fast_len(2 + (m-1), real=True)\n", + "N_upper_bound = next_fast_len(math.ceil(n/2) + (m-1), real=True)\n", + "\n", + "N_candidates = [N_lower_bound]\n", + "for N in range(N_lower_bound, N_upper_bound + 1):\n", + " if N <= N_candidates[-1]:\n", + " continue\n", + " N_candidates.append(next_fast_len(N, real=True))\n", + "N_candidates = np.array(N_candidates)\n", + "nchunks_candidates = np.ceil(n / (N_candidates - (m-1))).astype(int)\n", + "\n", + "with pd.option_context('display.max_rows', None):\n", + " print(pd.DataFrame({'N': N_candidates, 'nchunks': nchunks_candidates}))" + ] + }, + { + "cell_type": "markdown", + "id": "5e4287d6-9809-4ea1-b00f-54dbb53294b6", + "metadata": {}, + "source": [ + "In some cases, the same number of chunks can be associated with different values of `N`. In such case, we only want to get the smallest value of `N` as that is expected to be computationally less expensive." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "3585a0e1-5bc7-4cc5-98f2-e57251b5e002", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " N nchunks\n", + "0 270 274\n", + "1 288 125\n", + "2 300 92\n", + "3 320 64\n", + "4 324 60\n", + "5 360 40\n", + "6 375 35\n", + "7 384 32\n", + "8 400 29\n", + "9 405 28\n", + "10 432 24\n", + "11 450 22\n", + "12 480 19\n", + "13 486 18\n", + "14 500 17\n", + "15 512 16\n", + "16 540 15\n", + "17 576 13\n", + "18 600 12\n", + "19 640 11\n", + "20 675 10\n", + "21 720 9\n", + "22 768 8\n", + "23 864 7\n", + "24 960 6\n", + "25 1080 5\n", + "26 1280 4\n", + "27 1728 3\n", + "28 2304 2\n" + ] + } + ], + "source": [ + "_, IDX = np.unique(nchunks_candidates, return_index=True)\n", + "# Since N_candidates is sorted, the number of chunks will be sorted too\n", + "# and returning the first occurance of a new nchunk gives lowest value of N\n", + "\n", + "_, IDX = np.unique(nchunks_candidates, return_index=True)\n", + "N_candidates_pruned = np.sort(N_candidates[IDX])\n", + "nchunks_candidates_pruned = np.ceil(n / (N_candidates_pruned - (m-1))).astype(int)\n", + "with pd.option_context('display.max_rows', None):\n", + " print(pd.DataFrame({'N': N_candidates_pruned, 'nchunks': nchunks_candidates_pruned}))" + ] + }, + { + "cell_type": "markdown", + "id": "84345cd6-d456-4ed8-b160-39e1a00620aa", + "metadata": {}, + "source": [ + "As shown above, there are 29 candidates for \"N\" when `m = 2**8` and `n = 2**12`. Although we have only a few candidates of \"N\", finding the best \"N\" is still not cheap empirically. As an altenative approach, we can model the cost of computation and find the \"N\" that minimizes the cost." + ] + }, + { + "cell_type": "markdown", + "id": "831553b5", + "metadata": {}, + "source": [ + "## Mathematical model for the cost of computing valid convolution via circular convolution and overlap-add method\n", + "\n", + "For a query `Q` with the length of `m` and time series `T` with the length of `n`, the valid convolution can be achieved by one-shot N-circular convolution where `N = next_fast_len(n, real=True)` as follows:\n", + "\n", + "```{code}\n", + "# with FFT\n", + "IFFT(FFT(padded_Q) * FFT(padded_T))\n", + "\n", + "# with RFFT\n", + "IFFT(RFFT(padded_Q) * RFFT(padded_T))\n", + "```\n", + "\n", + "Let's review the cost of cicular convolution using FFT. We can then modify it so that it reflects the cost of RFFT-based circular convolution. The cost of FFT-based circular convolution consists of four major items:\n", + "\n", + "1. cost of FFT(padded_Q)\n", + "2. cost of FFT(padded_T)\n", + "3. Multiplication of two FFTs\n", + "4. IFFT of the multiplication\n", + "\n", + "Both `padded_Q` and `padded_T` are the length of `N = next_fast_len(n, real=True)`. To model the cost of FFT/IFFT, the following assumptions are made:\n", + "* `N` is an exact power of two\n", + "* Algorithm is radix-2 cooley-turkey\n", + "* The cost of FFT and IFFT are coming from their complex multiplication.\n", + "* The cost of computing twiddle factors, addition, substraction, and other operations are ignored.\n", + "\n", + "The radix-2 cooley-turkey algorithm has $log2(N)$ number of recursive stages. Each stage has $N/2$ number of butterflies and there is 1 complex multiplication per buterfly. Therefore, the total number of complex multiplication is $\\frac{N}{2}log2(N)$. So, the cost of circular convolution is:\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "c &= \\frac{N}{2}log2(N) + \\frac{N}{2}log2(N) + N + \\frac{N}{2}log2(N) \\\\\n", + " &= \\frac{N}{2}log2(N) + N(log2(N) + 1)\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "\n", + "In overlap-add, the cost is as follows:\n", + "1. cost of FFT(padded_Q): once \n", + "2. cost of FFT(paddded_chunk): per chunk\n", + "3. Mulitplication between FFT(padded_Q) and FFT(padded_chunk): per chunk\n", + "4. IFFT: per chunk\n", + "\n", + "Therefore, the cost is:\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "c\\_oa &= \\frac{N}{2}log2(N) + n\\_chunks \\times \\left(\\frac{N}{2}log2(N) + N + \\frac{N}{2}log2(N)\\right) \\\\\n", + "&= \\frac{N}{2}log2(N) + n\\_chunks \\times N(log2(N) + 1)\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "where $n\\_chunks = \\left\\lceil{\\frac{n}{N-(m-1)}}\\right\\rceil$. \n", + "\n", + "\n", + "Therefore:\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "c\\_oa &= \\frac{N}{2}log2(N) + \\left\\lceil{\\frac{n}{N-(m-1)}}\\right\\rceil * N(log2(N) + 1)\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "When the number of chunks, $\\left\\lceil{\\frac{n}{N-(m-1)}}\\right\\rceil$, is large, the first term (one-time cost of `FFT(padded_Q)`) can be ignored. Furthermore, the ceiling operator can be relaxed. Therefore:\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "c\\_oa &\\approx \\frac{n}{N-(m-1)} * N(log2(N) + 1) \\\\\n", + " &= n * \\frac{N(log2(N) + 1)}{N-(m-1)}\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "So, for a given $m$ and $n$, the value above is minimum when the fraction $\\frac{N(log2(N) + 1)}{N-(m-1)}$ is minimum. This is the same as (Eq. 3) in the [wikipedia page of overlap-add](https://en.wikipedia.org/wiki/Overlap–add_method). The optimal `N` can be computed by finding the minima of the approximate, simplified cost function $\\frac{N(log2(N) + 1)}{N-(m-1)}$. The closed form solution is used in the Scipy's function [_calc_oa_lens](https://github.com/scipy/scipy/blob/54ef5423f2e4376230ec3bfda6912a07a50958e3/scipy/signal/_signaltools.py#L717). The following derivation is the same as what provided as comment in the same Scipy function.\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "f(N) &= \\frac{N(log2(N) + 1)}{N-(m-1)} \\\\\n", + "&= \\frac{N}{N-(m-1)} * (log2(N) + 1) \\\\\n", + "&= \\frac{N}{N-(m-1)} * log2(2N) \\\\\n", + "&= \\frac{N}{N-(m-1)} * \\frac{ln(2N)}{ln2} \\\\\n", + "&= f1(N) * f2(N)\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "where $f1(N) = \\frac{N}{N-(m-1)}$ and $f2(N) = \\frac{ln(2N)}{ln2}$\n", + "\n", + "And the first step to find the optimal value is to solve $f'(N) = 0$. Let's compute $f'(N)$:\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "f'(N) &= f1'(N).f2(N) + f1(N).f2'(N) \\\\\n", + "&= \\frac{1*(N-(m-1)) - N*1}{(N-(m-1))^{2}}.\\frac{ln(2N)}{ln2} + \\frac{N}{N-(m-1)}.\\frac{1}{N*ln2}\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "Let's set $k = m - 1$. The equation above becomes:\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "f'(N) &= \\frac{-k}{(N-k)^{2}}.\\frac{ln(2N)}{ln2} + \\frac{N}{N-k}.\\frac{1}{N*ln2}\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "Let's solve it for $f'(N)=0$:\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "\\frac{k}{(N-k)^{2}}.\\frac{ln(2N)}{ln2} &= \\frac{N}{N-k}.\\frac{1}{N*ln2} \\\\ \n", + "\\frac{k \\times ln(2N)}{N-k} &= 1 \\\\ \n", + "N - k - k \\times ln(2N) &= 0 \\\\ \n", + "N &= k + k \\times ln(2N) \\\\ \n", + "N &= k(1 + ln(2N)) \\\\\n", + "N &= k \\times ln(2Ne) \\\\\n", + "N/k &= ln(2Ne) \\\\\n", + "e^{N/k} &= 2Ne \\\\\n", + "e^{N/k} &= 2(N/k)e * k \\\\\n", + "\\frac{1}{e^{N/k}} &= \\frac{1}{2(N/k)e * k} \\\\\n", + "e^{-N/k} &= \\frac{1}{(-N/k)} \\times \\frac{1}{-2e * k} \\\\\n", + "(-N/k)e^{-N/k} &= \\frac{1}{-2e * k} \\\\\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "At this point, we are looking for a solution for $y = xe^{x}$, where $y=\\frac{1}{-2e * k}$ is known and $x=-N/k$ is the unknown piece of equation. The solution for $y = xe^{x}$ is [the Lambert function](https://en.wikipedia.org/wiki/Lambert_W_function) $W$, i.e. $x=W(y)$. So:\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "\\frac{-N}{k} &= W(\\frac{-1}{2e*k}) \\\\\n", + "N &= -k \\times W(\\frac{-1}{2e*k}) \\\\\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "And plugging $k=m-1$ back into the equation above gives us the final solution: \n", + "\n", + "$$N = -(m-1) \\times W(\\frac{-1}{2e*(m-1)})$$\n", + "\n", + "The lambert function is a multivalued function. When its argument is between -1/e and 0, it can return two different values, one is `>= -1` and the other is `<= -1`. To know which value to choose, we should look at the original equation in the form of $y=xe^x$. Recall that the lambert function is to give us x, which is $\\frac{-N}{k}$, which is smaller than -1 since $N>k>0$ (Recall that `N=len(chunk) + m - 1`, and `k=m-1`). Therefore, the solution is only:\n", + "\n", + "$$N = -(m-1) \\times W_{-1}(\\frac{-1}{2e*(m-1)})$$\n", + "\n", + "where, $W_{-1}$ represents a certain part of lambert function that returns a value that is `<= -1`. As shown in [the Lambert function wikipedia page](https://en.wikipedia.org/wiki/Lambert_W_function), $W_{-1}$ gives negative value and it is strictly decreasing:\n", + "\n", + "* $m = 2 \\longrightarrow N = -(m-1) * (-2.678) = 2.68$\n", + "* $m = 3 \\longrightarrow N = -(m-1) * (-3.69) = 7.38$ \n", + "* ...\n", + "\n", + "According to assumption, $N$ is an exact power of two. Therefore, we should find the next number that is exact power of two. However, such change can be drastic when `m` is large and results in a value that is very larger than the computed $N$. Scipy uses `next_fast_len` to compute the closet value to $N$. Let's call it `next_fast_N`. This allows us to find the a \"good\" number (i.e. good for FFT factors) that is closer to the originally-computed $N$. This approch has a few caveats:\n", + "\n", + "* The value `next_fast_N` is not necessary an exact power of two, and hence the cost model will be less accurate.\n", + "* Scipy calls `scipy.fft.next_fast_len` but it passes the default value of `False` for the argument `real`. Therefore, it does not fully take advantage of algorithms when input arrays are real-valued.\n", + "* A certain length `n` can be divided by two different chunk size but result in the same number of chunks. In such case, it is often better to go with the smaller `chunk_size` having assumed that FFT is faster when the length is shorter. This means that `next_fast_N` is better to be replaced with the smallest value that gives the same number of chunks. " + ] + }, + { + "cell_type": "markdown", + "id": "814aed6b", + "metadata": {}, + "source": [ + "Now we need to see how the cost looks like when we use RFFT and IRFFT. RFFT can be seen as FFT on an array that is half of the length of input. Therefore, RFFT on an array of length `N` is equivalent to FFT on an array of length `N/2`. Hence, cost is $\\frac{N}{4}log2(\\frac{N}{2})$. If we follow \n", + "OTFFT approach, IRFFT has a preprocessing with `N/2` complex mulitplication (See `OTFFT`) followed by an IFFT on an array of length `N/2`. Therefore:\n", + "\n", + "1. cost of RFFT(padded_Q) --> $\\frac{N}{4}log2(\\frac{N}{2})$, once\n", + "2. cost of RFFT(padded_T) --> $\\frac{N}{4}log2(\\frac{N}{2})$, once per chunk\n", + "3. Multiplication of two RFFTs --> $\\frac{N}{2}$, once per chunk\n", + "4. IRFFT of the multiplication --> $\\frac{N}{2} + \\frac{N}{4}log2(\\frac{N}{2})$, once per chunk\n", + "\n", + "Note that, for an input array of length `N`, its RFFT has length `N/2 + 1`. For large `N`, this is approximately $\\frac{N}{2}$." + ] + }, + { + "cell_type": "markdown", + "id": "a4225c43", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{aligned}\n", + "c\\_oa &= \\frac{N}{4}log2(\\frac{N}{2}) + \\left\\lceil{\\frac{n}{N-(m-1)}}\\right\\rceil * \\left(\\frac{N}{4}log2(\\frac{N}{2}) + \\frac{N}{2} + (\\frac{N}{2} +\\frac{N}{4}log2(\\frac{N}{2}))\\right)\n", + "\\end{aligned}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "83bf1df2", + "metadata": {}, + "source": [ + "By following the same assumptions and approximations, we can get:\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "c\\_oa \\approx \\frac{n}{N-(m-1)} * \\left(\\frac{N}{2}log2(\\frac{N}{2}) + N\\right)\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "which can be rewritten as:\n", + "\n", + "$$\n", + "\\begin{aligned}\n", + "c\\_oa \\approx \\frac{n}{N-(m-1)} \\times \\frac{N}{2} \\times (log2(\\frac{N}{2}) + 2) \\\\\n", + "c\\_oa \\approx \\frac{n}{N-(m-1)} \\times \\frac{N}{2} \\times (log2(N) - 1 + 2) \\\\\n", + "c\\_oa \\approx \\frac{n}{2} \\times \\frac{N}{N-(m-1)} \\times (log2(N) + 1)\n", + "\\end{aligned}\n", + "$$\n", + "\n", + "which is half of the approximate cost of overlap-add when using FFT and IFFT. Therefore, the optimal solution will be the same as before:\n", + "\n", + "$$N = -(m-1) \\times W_{-1}(\\frac{-1}{2e*(m-1)})$$" + ] + }, + { + "cell_type": "markdown", + "id": "279f713b-10de-4159-b546-e79e43bfd1b2", + "metadata": {}, + "source": [ + "Note that the value `N` obtained from the equation above is not integer. So, to make sure we get the best closest `N`, we can follow Scipy's approach, which uses `next_fast_len(ceil(N), real=True)` instead. We can take one more step and compute its corresponding number of chunks, and see if the same number of chunks can be associated with a smaller size of `N`. This is shown in the function `compute_efficient_N` below" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "7b288476-d4d3-420f-992a-05a400a7fbb5", + "metadata": {}, + "outputs": [], + "source": [ + "def _compute_optimal_N(m):\n", + " overlap = m - 1\n", + " N = -overlap * lambertw(-1 / (2 * overlap * math.e), k=-1).real\n", + "\n", + " return N\n", + "\n", + "\n", + "def compute_efficient_N(m, n):\n", + " N = _compute_optimal_N(m)\n", + " fast_N = next_fast_len(math.ceil(N), real=True)\n", + "\n", + " # For same number of chunks, compute smallest N\n", + " chunk_size = fast_N - (m-1)\n", + " n_chunks = math.ceil(n / chunk_size) \n", + " optimized_fast_N = next_fast_len(math.ceil(n / n_chunks) + m - 1, real=True)\n", + "\n", + " return fast_N, optimized_fast_N\n", + "\n", + "fast_N, optimized_fast_N = compute_efficient_N(m, n)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "c532684e-c9a8-42d7-88a9-fdc8a215fa85", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "m: 256\n", + "n: 4096\n", + "fast_n for one-shot convolution: 4096\n", + "from model: fast_N (closed-form solution): 2430\n", + "from model: optimized fast_N (same number of chunks but smaller N if possible): 2304\n" + ] + } + ], + "source": [ + "print('m: ', m)\n", + "print('n: ', n)\n", + "\n", + "print('fast_n for one-shot convolution: ', next_fast_len(n, real=True))\n", + "print('from model: fast_N (closed-form solution): ', fast_N)\n", + "print('from model: optimized fast_N (same number of chunks but smaller N if possible): ', optimized_fast_N)" + ] + }, + { + "cell_type": "markdown", + "id": "d2c20217-c83c-4f61-b856-7358840b6518", + "metadata": {}, + "source": [ + "In this example, we can see that the next_fast_len of the closed-form solution is 2430. However, that was not included in `N_candidates_pruned`. N=2430 requires `ceil(4096/(2430 - (256-1)) = 2` chunks. For the same number of chunks, `next_fast_len(ceil(4096/2) + 256 - 1, real=True)` should suffice, and that gives 2304." + ] + }, + { + "cell_type": "markdown", + "id": "19c1cc34-6691-4061-bbe4-e315a054b93d", + "metadata": {}, + "source": [ + "**Regarding the example for `m=2^8` and `n=2^12`:** We can now plot the actual performance as well as the performane from cost model to see how close they are. In addition, there are four data points that are of our interest:\n", + "\n", + "* The actual performance at its maximum point\n", + "* The actual performance at a `N` that is the exact minima of cost model\n", + "* The actual performance at `N=2340`, which corresponds to the \"good\" length that is cloest to the minima of simplified cost function\n", + "* The actual performace at `N=2304`, which is the smallest \"good\" length `N` that has the same number of chunks as `N=2340`\n", + "\n", + "\n", + "In what follows, we put together the items discussed above and wrap them by functions so that we can check different cases." + ] + }, + { + "cell_type": "markdown", + "id": "802ac63a-5ee7-49dd-95ae-39635c9e739e", + "metadata": {}, + "source": [ + "### Code" + ] + }, + { + "cell_type": "markdown", + "id": "ce9f736b-3bd8-4864-9f3e-c23b124b1fc0", + "metadata": {}, + "source": [ + "```\n", + "# Code: Create a file within sdp, and run it \n", + "# via terminal for different mpower and npower\n", + "# python sdp.temp --mpower 8 --npower\n", + "\n", + "# note: m = 2^mpower, n = 2 ^ npower\n", + "\n", + "import argparse\n", + "import math\n", + "import numpy as np\n", + "import time\n", + "\n", + "from matplotlib import pyplot as plt\n", + "from scipy.fft import next_fast_len\n", + "from scipy.special import lambertw\n", + "from sdp.challenger_sdp import _valid_oaconvolve\n", + "from sdp.pocketfft_r2c_c2r_sdp import _valid_convolve\n", + "\n", + "# Check performane\n", + "MAX_ITER = 1000\n", + "TIMEOUT = 5.0\n", + "\n", + "\n", + "def timing_func(func, *args, **kwargs):\n", + " total, count = 0.0, 0\n", + " while count < MAX_ITER:\n", + " start = time.perf_counter()\n", + " func(*args, **kwargs)\n", + " total += time.perf_counter() - start\n", + " count += 1\n", + " if total > TIMEOUT:\n", + " break\n", + " return total / count\n", + "\n", + "\n", + "def _rfft_cost(N):\n", + " return (N / 4) * np.log2(N / 2)\n", + "\n", + "\n", + "def _irfft_cost(N):\n", + " return N / 2 + N / 4 * np.log2(N / 2)\n", + "\n", + "\n", + "def _cost_conv(N, n_chunks=1):\n", + " # When n_chunks=1 (default), it gives\n", + " # the cost of one-shot circular convolution\n", + "\n", + " rfft_c = _rfft_cost(N)\n", + " irfft_c = _irfft_cost(N)\n", + "\n", + " total_cost = rfft_c + n_chunks * ( # padded Q\n", + " rfft_c # padded chunk of T\n", + " + N / 2 # Multiplication between RFFT of Q and RFFT of chunk\n", + " + irfft_c # IRFFT on the outcome of multiplication\n", + " )\n", + "\n", + " return total_cost\n", + "\n", + "\n", + "def _compute_optimal_N(m):\n", + " overlap = m - 1\n", + " N = -overlap * lambertw(-1 / (2 * overlap * math.e), k=-1).real\n", + "\n", + " return N\n", + "\n", + "\n", + "def compute_efficient_N(m, n):\n", + " N = _compute_optimal_N(m)\n", + " fast_N = next_fast_len(math.ceil(N), real=True)\n", + "\n", + " # For same number of chunks, compute smallest N\n", + " chunk_size = fast_N - (m - 1)\n", + " n_chunks = math.ceil(n / chunk_size)\n", + " optimized_fast_N = next_fast_len(math.ceil(n / n_chunks) + m - 1, real=True)\n", + "\n", + " return fast_N, optimized_fast_N\n", + "\n", + "\n", + "def find_candidates(m, n):\n", + " N_lower_bound = next_fast_len(2 + (m - 1), real=True)\n", + " N_upper_bound = next_fast_len(math.ceil(n / 2) + (m - 1), real=True)\n", + "\n", + " N_candidates = [N_lower_bound]\n", + " for N in range(N_lower_bound, N_upper_bound + 1):\n", + " if N <= N_candidates[-1]:\n", + " continue\n", + " N_candidates.append(next_fast_len(N, real=True))\n", + " N_candidates = np.array(N_candidates)\n", + " nchunks_candidates = np.ceil(n / (N_candidates - (m - 1))).astype(int)\n", + "\n", + " _, IDX = np.unique(nchunks_candidates, return_index=True)\n", + " N_candidates_pruned = np.sort(N_candidates[IDX])\n", + "\n", + " return N_candidates_pruned\n", + "\n", + "\n", + "def plot_one_shot_vs_oa_conv(Q, T):\n", + " m = len(Q)\n", + " n = len(T)\n", + " N_candidates_pruned = find_candidates(m, n)\n", + "\n", + " # performance (actual)\n", + " timing_baseline = timing_func(_valid_convolve, Q, T)\n", + " timing_oa = np.empty(len(N_candidates_pruned), dtype=np.float64)\n", + " for i, N in enumerate(N_candidates_pruned):\n", + " chunk_size = N - (m - 1)\n", + " timing_oa[i] = timing_func(_valid_oaconvolve, Q, T, chunk_size)\n", + " print(f\"[{i+1} / {len(N_candidates_pruned)}]: N = {N}\")\n", + " performance_oa = timing_baseline / timing_oa\n", + "\n", + " # performance (acc to cost model)\n", + " timing_baseline_approx = _cost_conv(next_fast_len(n, real=True), n_chunks=1)\n", + " timing_oa_approx = np.empty(len(N_candidates_pruned), dtype=np.float64)\n", + " for i, N in enumerate(N_candidates_pruned):\n", + " chunk_size = N - (m - 1)\n", + " n_chunks = math.ceil(n / chunk_size)\n", + " timing_oa_approx[i] = _cost_conv(N, n_chunks=n_chunks)\n", + " performance_oa_approx = timing_baseline_approx / timing_oa_approx\n", + "\n", + " # closed form solution\n", + " fast_N, optimized_fast_N = compute_efficient_N(m, n)\n", + "\n", + " # plot\n", + " plt.figure(figsize=(15, 5))\n", + " plt.title(f\"m={m}, n={n}, oa_convolve\")\n", + "\n", + " plt.plot(performance_oa, color=\"k\", label=\"performance (actual)\")\n", + " plt.plot(\n", + " performance_oa_approx, color=\"gray\", linestyle=\"--\", label=\"performance (model)\"\n", + " )\n", + "\n", + " idx = np.argmax(performance_oa)\n", + " value = performance_oa[idx]\n", + " plt.scatter(idx, value, marker=\"D\", color=\"b\", label=f\"max (actual)={value}\")\n", + "\n", + " idx = np.argmax(performance_oa_approx)\n", + " value = performance_oa[idx]\n", + " plt.scatter(idx, value, marker=\"o\", color=\"r\", label=f\"max (acc to model)={value}\")\n", + " plt.axvline(idx, linestyle=\":\", color=\"r\")\n", + "\n", + " if fast_N < n:\n", + " # fast_N from closed-form solution\n", + " timing_fast_N = timing_func(\n", + " _valid_oaconvolve, Q, T, fast_N - (m - 1) # chunk size\n", + " )\n", + " value = timing_baseline / timing_fast_N\n", + " plt.axhline(\n", + " value,\n", + " linestyle=\"--\",\n", + " color=\"purple\",\n", + " label=f\"est max (acc to simplified model)={value} @ N={fast_N}\",\n", + " )\n", + " else:\n", + " print(f\"fast_N={fast_N} > {n}\")\n", + "\n", + " if optimized_fast_N in N_candidates_pruned:\n", + " idx = np.flatnonzero(N_candidates_pruned == optimized_fast_N)[0]\n", + " value = performance_oa[idx]\n", + " plt.scatter(\n", + " idx,\n", + " value,\n", + " marker=\"*\",\n", + " color=\"orange\",\n", + " label=f\"optimized est max (acc to simplified model)={value}\",\n", + " )\n", + " else:\n", + " print(f\"optimized_fast_N={optimized_fast_N} > {N_candidates_pruned.max()}\")\n", + "\n", + " plt.xticks(\n", + " ticks=np.arange(len(N_candidates_pruned)),\n", + " labels=N_candidates_pruned,\n", + " rotation=90,\n", + " )\n", + " plt.xlabel(\"N, the length of circular convolution\")\n", + " plt.legend()\n", + " plt.grid()\n", + "\n", + " plt.savefig(f\"oa_m_{m}_n_{n}.png\", dpi=300, bbox_inches=\"tight\")\n", + " plt.show()\n", + "\n", + "\n", + "if __name__ == \"__main__\":\n", + " parser = argparse.ArgumentParser()\n", + "\n", + " parser.add_argument(\"--mpower\", type=int, required=True)\n", + " parser.add_argument(\"--npower\", type=int, required=True)\n", + "\n", + " args = parser.parse_args()\n", + " m = args.mpower\n", + " n = args.npower\n", + "\n", + " Q = np.random.rand(2**m)\n", + " T = np.random.rand(2**n)\n", + "\n", + " plot_one_shot_vs_oa_conv(Q, T)\n", + "\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "8c2322c3-8f37-4970-823e-d286235e35e8", + "metadata": {}, + "source": [ + "### Examples" + ] + }, + { + "cell_type": "markdown", + "id": "12f88da2-6bf3-4046-8d00-2184261f9411", + "metadata": {}, + "source": [ + "In the figures below, the x-axis shows the size of each circular convolution in overlap-add. The black curve shows the actual performance for overlap-add w.r.t one-shot circular convolution. So, any point `N` on the black curve that is above `y=1.0` means that the overlap-add with circular convolution of size `N` outperforms the one-shot circular convolution. The true maximum of this curve is shown as \"blue diamond\" marker As mentioned before, achieving this true optimal point is not cheap.\n", + "\n", + "The dashed, gray curve shows the performance computed based on cost model. So, any point `N` on the gray curve that is `above y=1.0` means that the computational cost of overlap-add with circular convolution of size `N` is lower than the computational cost of one-shot circular convolution. The true maximum of this curve is shown as \"red circle\" marker. Finding the true optimal point on this curve is less expensive but still not cheap. We can use the lambert function to use the closed-form solution for calculating the optimal point of the simplified version of the cost model. This `N` might not exist in the candidates of `N` considered when plotting the figure. So, we show its performance using horziental purple line. For the computed `N`, we calculate the number of chunks, and accordingly, recompute the smallest `N` that satisfies the same number of chunks. This is shown with \"yellow star\" marker. If we are luckly, we should see:\n", + "\n", + "* The true maximum of actual performance and the true maximum of cost-model-based performance are both greater than 1.0. Or, they are both lower than 1.0\n", + "* The true maximum of actual performance and the actual performance at the maxima of cost-model-based performance are corresponding to the same `N`\n", + "* The true maxima and the estimated one in cost-model-based performance are close to each other." + ] + }, + { + "cell_type": "markdown", + "id": "66fc84bd-7eff-4904-890a-f333afa9f036", + "metadata": {}, + "source": [ + "### m=2^8, n=2^12" + ] + }, + { + "cell_type": "markdown", + "id": "38529f98-925d-4094-912e-1a275d1a5d92", + "metadata": {}, + "source": [ + "![Alt text](oa_performance_figures/oa_m_256_n_4096.png)" + ] + }, + { + "cell_type": "markdown", + "id": "f919f983-cf27-4c54-bc0f-1c1aa13405a3", + "metadata": {}, + "source": [ + "We are lucky that the maximum of actual performance and the cost-model-based performance are both corresponding to the same `N=1280`. However, according to cost model, overlap-add with `N=1280` should have lower cost than one-shot circular convolution. However, we can see that the best actual performance from overlap-add, which is at `N=1280`, is worse. It is 0.8x of the one-shot circular convolution. `20%` reduction in performance might be ok depending on the gain one get in other cases. Let's check others." + ] + }, + { + "cell_type": "markdown", + "id": "bb4d44b3-a403-4acc-8094-e45cd87091a7", + "metadata": {}, + "source": [ + "### m=2^10, n=2^15" + ] + }, + { + "cell_type": "markdown", + "id": "3abb0152-6e0c-485d-b6cc-2e24c4b05783", + "metadata": {}, + "source": [ + "![Alt text](oa_performance_figures/oa_m_1024_n_32768.png)" + ] + }, + { + "cell_type": "markdown", + "id": "318c4994-b76f-4ded-bec8-639115c50c68", + "metadata": {}, + "source": [ + "In this example, we are again lucky that the true maxima of actual performance (black curve) and the true maxima performance obtained based on cost model (dotted gray curve) are both corresponding to the same `N=5120`. Note that the closed-form solution gave `N=11520`, and its performance is shown with horizental purple line. Note that this is not included in the values on the x-axis. This is because `N=11520` requires `ceil(32768 / (11520 - (1024-1))) = 4` chunks. However, for the same number of chunks, we only need circular convolution of size `next_fast_len(ceil(32768/4)+1024-1, real=True)=9216`, which is shown with \"yellow star\" marker. Note that the overlap-add with `N=9216` is 1.4x faster than one-shot convolution but the overlap-add with `N=11520` is 1.1x faster." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.14.4" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/docs/oa_performance_figures/oa_m_1024_n_32768.png b/docs/oa_performance_figures/oa_m_1024_n_32768.png new file mode 100644 index 0000000..2f2ad13 Binary files /dev/null and b/docs/oa_performance_figures/oa_m_1024_n_32768.png differ diff --git a/docs/oa_performance_figures/oa_m_256_n_4096.png b/docs/oa_performance_figures/oa_m_256_n_4096.png new file mode 100644 index 0000000..5bdda2b Binary files /dev/null and b/docs/oa_performance_figures/oa_m_256_n_4096.png differ diff --git a/sdp/challenger_sdp.py b/sdp/challenger_sdp.py index ce60e8d..d5451b0 100644 --- a/sdp/challenger_sdp.py +++ b/sdp/challenger_sdp.py @@ -1,14 +1,189 @@ +import math import numpy as np +from scipy.fft import next_fast_len +from scipy.special import lambertw +from sdp import pocketfft_r2c_c2r_sdp + +# _duccfft replaced _pocketfft in scipy 1.18 +try: + from scipy.fft._duccfft.basic import c2r, r2c +except ModuleNotFoundError: # pragma: no cover + from scipy.fft._pocketfft.basic import c2r, r2c + + +def _optimize_oa_cir_size(m, n): + """ + Compute a potentially-optimized value for the size of + circular convolution in overlap-add + + Parameters + ---------- + m : int + The length of query + + n : int + The length of time series + + Returns + ------- + out : int + The size of chunk in overlap-add + """ + N = -(m - 1) * lambertw(-1 / (2 * (m - 1) * math.e), k=-1).real + N = next_fast_len(math.ceil(N), real=True) + + # For the computed N, we measure the number of chunks, + # and recompute N to obtain smaller `N` if possible + # Example: + # n = 100 + # m = 6 + # N = 45 + # chunk_size = N - (m-1) = 40 + # n_chunk = ceil(n/chunk_size) = 3 + # N = ceil(n/n_chunk) + m - 1 = 39 + # next_fast_len(40, real=True) = 40 + # 40 is smaller than 45, the original N + n_chunks = math.ceil(n / (N - (m - 1))) + return next_fast_len(math.ceil(n / n_chunks) + (m - 1), real=True) + + +def _valid_oaconvolve(Q, T, chunk_size): + """ + Compute the valid convolution between Q and T using the overlap-add method. + + `T` is split into non-overlapping chunks of `chunk_size` elements + (the last chunk may be shorter). Each chunk is fully convolved with `Q`, + and the chunk results are summed at their proper offsets (overlap-add), + which gives the full linear convolution between `Q` and `T`. Finally, + only the "valid" part is kept. + + Parameters + ---------- + Q : numpy.ndarray + Query array or subsequence + + T : numpy.ndarray + Time series or sequence + + chunk_size : int + Number of elements of `T` in each chunk. Must be at least 1. + + Returns + ------- + out : numpy.ndarray + The valid convolution between Q and T, of length `len(T) - len(Q) + 1`. + """ + m = len(Q) + n = len(T) + num_chunks = math.ceil(n / chunk_size) + next_divisble_n = num_chunks * chunk_size + + # Zero-pad T so the last chunk is full-sized, then view it as + # (num_chunks, chunk_size). This padding only makes the chunks equal-sized; + T_padded = np.empty(next_divisble_n, dtype=np.float64) + T_padded[:n] = T + T_padded[n:] = 0.0 + chunks = T_padded.reshape(num_chunks, chunk_size) + + # Linear conv of a chunk (of length `chunk_size`) with Q (of length `m``) + # has length `N = chunk_size + m - 1`. An N-circular conv of that size equals + # the full linear convolution between the chunk and Q. The convolution between + # Q and each chunk is computed. + + N = chunk_size + m - 1 + chunk_convs = c2r( + False, + r2c(True, chunks, n=N, axis=-1) * r2c(True, Q, n=N), + n=N, + axis=-1, + ) # shape: (num_chunks, N) + + out = np.zeros(next_divisble_n + m - 1, dtype=np.float64) + for i, chunk_conv in enumerate(chunk_convs): + start = i * chunk_size + out[start : start + N] += chunk_conv + + # Keep only the "valid" part, where Q fully overlaps T (length n - m + 1). + # Anything at index >= n comes from the zero padding and is discarded. + return out[m - 1 : n] + + +def _valid_convolve(Q, T, chunk_size=None): + """ + Compute the valid convolution between Q and T. + + The overlap-add method is used unless `chunk_size` is smaller than 1 + or covers all of `T`, in which case no chunking is done. + + Parameters + ---------- + Q : numpy.ndarray + Query array or subsequence. + + T : numpy.ndarray + Time series or sequence. + + chunk_size : int, default None + Number of elements of `T` in each chunk of the overlap-add method. + If None, `len(T) // 2` is used. + + Returns + ------- + out : numpy.ndarray + The valid convolution between Q and T, of length + `len(T) - len(Q) + 1`. + + Notes + ----- + The valid convolution between ``Q`` and ``T`` is equivalent to + the sliding dot product between Q[::-1] and T. + """ + m = len(Q) + n = len(T) + if chunk_size is None: + N = _optimize_oa_cir_size(m, n) + else: + N = chunk_size + m - 1 + + next_fast_n = next_fast_len(n, real=True) + if N < next_fast_n: + # ToDo: Maybe add check for approx cost ratio < 1.0 + return _valid_oaconvolve(Q, T, N - (m - 1)) + + return pocketfft_r2c_c2r_sdp._valid_convolve(Q, T) + def setup(Q, T): return -def sliding_dot_product(Q, T): - m = len(Q) - l = T.shape[0] - m + 1 - out = np.empty(l) - for i in range(l): - out[i] = np.dot(Q, T[i : i + m]) - return out +def sliding_dot_product(Q, T, chunk_size=None): + """ + Compute the sliding dot product between Q and T. + + Parameters + ---------- + Q : numpy.ndarray + Query array or subsequence. + + T : numpy.ndarray + Time series or sequence. + + chunk_size : int, default None + Number of elements of `T` per chunk in the overlap-add convolution. + See `_valid_convolve`. + + Returns + ------- + out : numpy.ndarray + The sliding dot product between Q and T, of length + `len(T) - len(Q) + 1`. + """ + if len(Q) == len(T): + # Only one window, so the result is a single dot product + return np.array([np.dot(Q, T)]) + + # Convolution is a flip-and-slide. So, flipping Q first turns the + # convolution into a sliding dot product. + return _valid_convolve(Q[::-1], T, chunk_size=chunk_size) diff --git a/sdp/pocketfft_r2c_c2r_sdp.py b/sdp/pocketfft_r2c_c2r_sdp.py index cd6d73e..a4cce6a 100644 --- a/sdp/pocketfft_r2c_c2r_sdp.py +++ b/sdp/pocketfft_r2c_c2r_sdp.py @@ -8,20 +8,30 @@ from scipy.fft._pocketfft.basic import c2r, r2c -def setup(Q, T): - return - - -def sliding_dot_product(Q, T): +def _valid_convolve(Q, T): + """ + Compute the valid convolution between ``Q`` and ``T`` + using circular convolution in the frequency domain + """ n = len(T) m = len(Q) next_fast_n = next_fast_len(n, real=True) tmp = np.empty((2, next_fast_n)) - tmp[0, :m] = Q[::-1] + tmp[0, :m] = Q tmp[0, m:] = 0.0 tmp[1, :n] = T tmp[1, n:] = 0.0 fft_2d = r2c(True, tmp, axis=-1) - return c2r(False, np.multiply(fft_2d[0], fft_2d[1]), n=next_fast_n)[m - 1 : n] + return c2r(False, np.multiply(fft_2d[0], fft_2d[1]), n=next_fast_n)[ + len(Q) - 1 : len(T) + ] + + +def setup(Q, T): + return + + +def sliding_dot_product(Q, T): + return _valid_convolve(Q[::-1], T) diff --git a/test.py b/test.py index d1b80e8..1cad6df 100644 --- a/test.py +++ b/test.py @@ -119,7 +119,7 @@ def test_sdp(n_T, remainder, comparator): 97, ] n_Q_power2 = [2, 4, 8, 16, 32, 64] - n_Q_values = n_Q_prime + n_Q_power2 + [n_T] + n_Q_values = n_Q_prime + n_Q_power2 + [n_T - 1, n_T] n_Q_values = sorted(n_Q for n_Q in set(n_Q_values) if n_Q <= n_T) modules = utils.import_sdp_mods() @@ -210,3 +210,19 @@ def test_pyfftw_sdp_max_n(): np.testing.assert_allclose(comp, ref) return + + +def test_oaconvolve_sdp(): + from sdp.challenger_sdp import sliding_dot_product + + T = np.random.rand(2**10) + Q = np.random.rand(2**8) + + m = len(Q) + n = len(T) + ref = naive_sliding_dot_product(Q, T) + for chunk_size in [1, m - 1, m, m + 1, n // 2, n - 1, n, None]: + comp = sliding_dot_product(Q, T, chunk_size=chunk_size) + np.testing.assert_allclose(comp, ref) + + return