The provided code implements a neural network evaluation for a chess engine, with a quantized first layer followed by floating-point layers. Let's break down the matrix multiplication and the implications of using hardswish activation.
Matrix Multiplications (Matmuls) for Layer 1:
The first layer takes a 20480-dimensional input (represented by the in_weights array) and projects it down to 1536 dimensions (before ReLU, equivalent to two 768-dimension "halfkp" components). Since L1SIZE = 1536 and L2SIZE = 8, the core computation within halfkp_relu_quant_affine_relu effectively performs a 20480x8 matmul (or two 10240x8 matmuls if you consider the "halfkp" structure) followed by a ReLU activation and quantization. This is done 8 output neurons at a time (within the outer loop iterating OutChunks times). Inside this loop, the code iterates through input chunks (InChunks) performing multiple multiply-accumulate operations to calculate the output for each of the 8 neurons.
So, to be precise, a single 20480x8 matrix multiplication is performed (logically), which is broken down into smaller multiply-accumulate operations for efficiency. The "halfkp" structure doesn't change the number of matmul operations needed; it just organizes the data and computation.
[Redacted Person] vs. ReLU Cycles:
The current code uses ReLU, which is computationally very cheap. It's a simple comparison and assignment: max(0, x). In the provided code, this is implemented using intrinsic instructions like _mm256_max_epi32 (AVX2) or _mm_max_epi32 (AVX), which are highly optimized and take very few cycles.
Hardswish, while offering some advantages in terms of gradient properties, is more complex. The standard definition is:
hardswish(x) = x * max(0, min(1, x + 3)) / 6
This involves several operations:
- Addition:
x + 3
- Min:
min(1, x + 3)
- Max:
max(0, min(1, x + 3))
- Multiplication:
x * ...
- Division:
/ 6
Each of these adds cycles compared to the single max operation of ReLU. While some optimizations can be made with intrinsics (especially for the min/max and vectorized arithmetic), hardswish will still be significantly more expensive. The division by 6 is particularly costly. A common approximation to hardswish uses a piecewise function:
hardswish(x) = 0 if x <= -3
= x * (x + 3) / 6 if -3 < x < 3
= x if x >= 3
This involves branching, which can introduce further performance penalties due to branch mispredictions.
Estimating Cycle Difference:
It's difficult to give a precise cycle count difference without benchmarking on a specific architecture. However, a rough estimate would be that hardswish could take anywhere from 3-10 times more cycles than ReLU, depending on the implementation and hardware. This is a substantial difference and would likely have a noticeable impact on the engine's evaluation speed. The exact cost would need to be profiled. If speed is critical, using ReLU provides a significant advantage.