A Bitwise Convolution Tutorial
1 October 2018Prerequisites
An introduction
It is an important and popular fact that the things that we classify as FFT on code-drills, are not always actual fast fourier transforms (if we're being overly-technical). Suppose you are given two arrays and and an operation . We will call the convolution of and the array , such that:
In the case of actual FFT, is addition, but it might as well be something else, like AND, OR, XOR, or something like gcd or lcm that require techniques far less advanced than the ones presented in this article, intended to introduce the (*sighs* rare) reader to techniques that allow us to efficiently compute such convolutions by linear algebraic means. I will also present the solutions to some problems that involve these techniques such as Random Nim Generator.
Throwback to FFT
As you should know, FFT is basically a divide and conquer algorithm designed to reduce the complexity of the multiplication of a vector with a specific Vandermonde matrix:
Let's recap a bit the FFT process:
-
We define the product operation on two vectors as the following: given two vectors and , , where and
* Note: Despite the horrific notation colision, in the reminder of the article will denote the number of elements in the corresponding array of vector .
-
Using the definition, the operation uses time, so we resize our vectors to the smallest power of two larger than (let that power of two be ). And multiply each of these vectors with to obtain and . We define , where denotes element by element multiplication (e.g.: ), and we multiply with to obtain the desired matrix. In short:
where and have already been resized to . This works because our operation is equivalent to polynomial multiplication, and multiplying a vector with esentially evaluates a polynomial at the roots of unity:
So is equal to the product of the corresponding polynomials of and evaluated at and multiplying the vector with basically interpolates the polynomial from the values evaluated at all these roots of unity.
Now let's see how we multiply such a vector with fast, or because FFT is among the prerequisites, why the algorithm works from a linear algebraic point of view.
Basically, after applying a permutation to the initial vector, at each level (value of step), it divides the sequence into buckets of length step*2 and multiplies the vector correspondent to that bucket with a matrix that looks like this:
Multiplying with takes time, because the matrix is sparse. This multiplication is found in the for (int pos = 0; ...) loop. Now as you might expect, FFT basically decomposes into a product of these matrices and a permutation matrix. So
Where '' denotes the Kronecker product, a key operation troughout the whole of this article and you must know at least its definition to grasp the remainder of this article. In this particular case, you may interpret it as is applied on all the buckets (i.e. the Kroneker product distributes the multiplication on each of the buckets). The proof of the equivalence of this decomposition to is based on induction and quite beyond the scope of this article.
int rev(int x, int l) { // mirror the bits (e.g. 01011 -> 11010)
int res = 0;
for (int bit = 0; bit < l; ++bit) {
res*= 2;
res|= x & 1;
x/= 2;
}
return res;
}
void fft(vector<Complex> &pol, int inverse = 1) {
int n = size(pol);
for (int i = 0; i < n; ++i)
if (i < rev(i, log2[n]))
swap(pol[i], pol[rev(i, log2[n])]);
for (int step = 1; step < n; step*= 2) {
Complex root;
root.r = cos(inverse * PI / step); // real part
root.i = sin(inverse * PI / step); // imaginary part
for (int pos = 0; pos < n; pos+= step * 2) {
Complex omega = 1;
for (int i = 0; i < step; ++i) {
Complex x = pol[pos + i];
Complex y = pol[pos + i + step] * omega;
omega*= root;
pol[pos + i] = x + y;
pol[pos + i + step] = x - y;
}
}
if (inverse == -1)
for (int i = 0; i < n; ++i)
pol[i]*= 0.5;
}
}int rev(int x, int l) { // mirror the bits (e.g. 01011 -> 11010)
int res = 0;
for (int bit = 0; bit < l; ++bit) {
res*= 2;
res|= x & 1;
x/= 2;
}
return res;
}
void fft(vector<Complex> &pol, int inverse = 1) {
int n = size(pol);
for (int i = 0; i < n; ++i)
if (i < rev(i, log2[n]))
swap(pol[i], pol[rev(i, log2[n])]);
for (int step = 1; step < n; step*= 2) {
Complex root;
root.r = cos(inverse * PI / step); // real part
root.i = sin(inverse * PI / step); // imaginary part
for (int pos = 0; pos < n; pos+= step * 2) {
Complex omega = 1;
for (int i = 0; i < step; ++i) {
Complex x = pol[pos + i];
Complex y = pol[pos + i + step] * omega;
omega*= root;
pol[pos + i] = x + y;
pol[pos + i + step] = x - y;
}
}
if (inverse == -1)
for (int i = 0; i < n; ++i)
pol[i]*= 0.5;
}
}The Bitwise Convolutions Matrices
Now that there we're done with the short "classical FFT" recap, we may dive into XOR, AND and OR covolutions, and there is good news! They are quite easier to understand, don't require complex numbers or roots of unity in some field, run much faster and are shorter to code. All of that matrix decomposition maths was there to point out the fact that most convolution algorithms (but not gcd convolution for example) are based on such matrix decompositions and present a familiar example, even though it is one of the most complex ones from this perspective. Remember the relation from the beginning of the article? Let's change to (for "transformation") to avoid confusion. Now the meaning of is that we apply some transformation to each of the vectors, obtain another vector trough one by one multiplication ('') and then reverse the transformation in order to get the result of the convolution. Looking at this equation from above, (the transformation) is the unknown. In the case of "classical FFT", the vandermonde matrix over the roots of unity worked, but now we must find another that yelds the XOR convolution for example. Let's see how we find out the values of in that case! We will use as the operator symbol of XOR, as it is shorter and looks fancier and \$$ as the XOR convolution symbol. Also, n$ will be a power of two to ensure that everything is contained. Let's see how this convolution would work for vectors of size 2. By definition:
Additionally:
And we'll set
So now we can start solving for .
Now, because are variables, this gives us a system of equations:
Which has the following solutions:
But there is a catch, must be invertible. That is , which leaves us with these solutions
And indeed, these are the the matrices whose correspondend transformation gives us the XOR convolution for arrays of length . So we'd better figure out a way to extend this to larger powers of 2, let's say . Then, the transformation matrix would be , which in our case is the Hadamard Matrix. The proof of this, again is based on induction (and actually not that hard) and will appear in case of popular demand. But the main principle behind it is that for XOR, OR and AND, the bits are independent and the Kroenenker product has a distributive multiplication efect, as in the case of "classical FFT", on the sequence partitioned in buckets of size 2, then 4, then 8 etc. There's just one more thing to point out about the kroneker product:
Let's see how we efficiently multiply these kroneker products with vectors if
And in case you want a XOR convolution, just set to the values from the specific XOR transformation matrix.
void transform(vector<double> &pol) {
int n = size(pol);
for (int step = 1; step < n; step*= 2) {
for (int pos = 0; pos < n; pos+= step * 2) {
for (int i = 0; i < len; ++i) {
// replace values pol[pos + i] pol[pos + 1 + step] with their product with T_2
double a = pol[pos + i];
double b = pol[pos + i + step];
pol[pos + i] = w * a + x * b;
pol[pos + i + step] = y * a + z * b;
}
}
}
}
void inverse_transform(vector<double> &pol) {
const double determinant = w * z - x * y;
int n = size(pol);
for (int step = 1; step < n; step*= 2) {
for (int pos = 0; pos < n; pos+= step * 2) {
for (int i = 0; i < len; ++i) {
// replace values pol[pos + i] pol[pos + 1 + step] with their product with the inverse of T_2
double a = pol[pos + i];
double b = pol[pos + i + step];
pol[pos + i] = (z * a - y * b) / determinant;
pol[pos + i + step] = (w * b - x * a) / determinant;
}
}
}
}void transform(vector<double> &pol) {
int n = size(pol);
for (int step = 1; step < n; step*= 2) {
for (int pos = 0; pos < n; pos+= step * 2) {
for (int i = 0; i < len; ++i) {
// replace values pol[pos + i] pol[pos + 1 + step] with their product with T_2
double a = pol[pos + i];
double b = pol[pos + i + step];
pol[pos + i] = w * a + x * b;
pol[pos + i + step] = y * a + z * b;
}
}
}
}
void inverse_transform(vector<double> &pol) {
const double determinant = w * z - x * y;
int n = size(pol);
for (int step = 1; step < n; step*= 2) {
for (int pos = 0; pos < n; pos+= step * 2) {
for (int i = 0; i < len; ++i) {
// replace values pol[pos + i] pol[pos + 1 + step] with their product with the inverse of T_2
double a = pol[pos + i];
double b = pol[pos + i + step];
pol[pos + i] = (z * a - y * b) / determinant;
pol[pos + i + step] = (w * b - x * a) / determinant;
}
}
}
}Some Pen and Paper Exercises
- Find for OR and AND transforms
- Given an operation that "ORs" the first bit, "ANDs" the second bit, "XORs" the third one and then repeats, find the transformation matrix for such a convolution on arrays of bits (of length ).
- Find a transformation matrix where the operation is XOR but in base 3 (addition with no carry).
Random Nim Generator
"How many sequences of length containing numbers from to have their total XOR sum greater than ?" Let's see a dp approach!
where is the number of elements taken so far and is their current XOR sum. And the dp is initialized with . Let's define (the first k + 1 values are and the rest are , the array's length being the smallest power of greater or equal to ). Now we can write the recurrence as
So you just have to use the XOR transform on convolute it with itself times and output the sum of the values of the non-zero positions of the resulting vector. Here is my source code.
AND closure
Just apply a "self-AND-convolution" to the frequency array log times and output the positions with non-zero corresponding values. Here is my source code.