2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2023 The Stockfish developers (see AUTHORS file)
5 Stockfish is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 Stockfish is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
19 // Definition of layer AffineTransformSparseInput of NNUE evaluation function
21 #ifndef NNUE_LAYERS_AFFINE_TRANSFORM_SPARSE_INPUT_H_INCLUDED
22 #define NNUE_LAYERS_AFFINE_TRANSFORM_SPARSE_INPUT_H_INCLUDED
29 #include "../../bitboard.h"
30 #include "../nnue_common.h"
31 #include "affine_transform.h"
35 This file contains the definition for a fully connected layer (aka affine transform) with block sparse input.
38 namespace Stockfish::Eval::NNUE::Layers {
40 #if (USE_SSSE3 | (USE_NEON >= 8))
41 alignas(CacheLineSize) static inline const std::array<std::array<std::uint16_t, 8>, 256> lookup_indices = [](){
42 std::array<std::array<std::uint16_t, 8>, 256> v{};
43 for (unsigned i = 0; i < 256; ++i)
45 std::uint64_t j = i, k = 0;
47 v[i][k++] = pop_lsb(j);
52 // Find indices of nonzero numbers in an int32_t array
53 template<const IndexType InputDimensions>
54 void find_nnz(const std::int32_t* input, std::uint16_t* out, IndexType& count_out) {
55 #if defined (USE_SSSE3)
56 #if defined (USE_AVX512)
57 using vec_t = __m512i;
58 #define vec_nnz(a) _mm512_cmpgt_epi32_mask(a, _mm512_setzero_si512())
59 #elif defined (USE_AVX2)
60 using vec_t = __m256i;
61 #if defined(USE_VNNI) && !defined(USE_AVXVNNI)
62 #define vec_nnz(a) _mm256_cmpgt_epi32_mask(a, _mm256_setzero_si256())
64 #define vec_nnz(a) _mm256_movemask_ps(_mm256_castsi256_ps(_mm256_cmpgt_epi32(a, _mm256_setzero_si256())))
66 #elif defined (USE_SSSE3)
67 using vec_t = __m128i;
68 #define vec_nnz(a) _mm_movemask_ps(_mm_castsi128_ps(_mm_cmpgt_epi32(a, _mm_setzero_si128())))
70 using vec128_t = __m128i;
71 #define vec128_zero _mm_setzero_si128()
72 #define vec128_set_16(a) _mm_set1_epi16(a)
73 #define vec128_load(a) _mm_load_si128(a)
74 #define vec128_storeu(a, b) _mm_storeu_si128(a, b)
75 #define vec128_add(a, b) _mm_add_epi16(a, b)
76 #elif defined (USE_NEON)
77 using vec_t = uint32x4_t;
78 static const std::uint32_t Mask[4] = {1, 2, 4, 8};
79 #define vec_nnz(a) vaddvq_u32(vandq_u32(vtstq_u32(a, a), vld1q_u32(Mask)))
80 using vec128_t = uint16x8_t;
81 #define vec128_zero vdupq_n_u16(0)
82 #define vec128_set_16(a) vdupq_n_u16(a)
83 #define vec128_load(a) vld1q_u16(reinterpret_cast<const std::uint16_t*>(a))
84 #define vec128_storeu(a, b) vst1q_u16(reinterpret_cast<std::uint16_t*>(a), b)
85 #define vec128_add(a, b) vaddq_u16(a, b)
87 constexpr IndexType InputSimdWidth = sizeof(vec_t) / sizeof(std::int32_t);
88 // Inputs are processed InputSimdWidth at a time and outputs are processed 8 at a time so we process in chunks of max(InputSimdWidth, 8)
89 constexpr IndexType ChunkSize = std::max<IndexType>(InputSimdWidth, 8);
90 constexpr IndexType NumChunks = InputDimensions / ChunkSize;
91 constexpr IndexType InputsPerChunk = ChunkSize / InputSimdWidth;
92 constexpr IndexType OutputsPerChunk = ChunkSize / 8;
94 const auto inputVector = reinterpret_cast<const vec_t*>(input);
96 vec128_t base = vec128_zero;
97 const vec128_t increment = vec128_set_16(8);
98 for (IndexType i = 0; i < NumChunks; ++i)
100 // bitmask of nonzero values in this chunk
102 for (IndexType j = 0; j < InputsPerChunk; ++j)
104 const vec_t inputChunk = inputVector[i * InputsPerChunk + j];
105 nnz |= unsigned(vec_nnz(inputChunk)) << (j * InputSimdWidth);
107 for (IndexType j = 0; j < OutputsPerChunk; ++j)
109 const auto lookup = (nnz >> (j * 8)) & 0xFF;
110 const auto offsets = vec128_load(reinterpret_cast<const vec128_t*>(&lookup_indices[lookup]));
111 vec128_storeu(reinterpret_cast<vec128_t*>(out + count), vec128_add(base, offsets));
112 count += popcount(lookup);
113 base = vec128_add(base, increment);
120 # undef vec128_set_16
122 # undef vec128_storeu
126 // Sparse input implementation
127 template <IndexType InDims, IndexType OutDims>
128 class AffineTransformSparseInput {
131 using InputType = std::uint8_t;
132 using OutputType = std::int32_t;
134 // Number of input/output dimensions
135 static constexpr IndexType InputDimensions = InDims;
136 static constexpr IndexType OutputDimensions = OutDims;
138 static_assert(OutputDimensions % 16 == 0, "Only implemented for OutputDimensions divisible by 16.");
140 static constexpr IndexType PaddedInputDimensions =
141 ceil_to_multiple<IndexType>(InputDimensions, MaxSimdWidth);
142 static constexpr IndexType PaddedOutputDimensions =
143 ceil_to_multiple<IndexType>(OutputDimensions, MaxSimdWidth);
145 #if (USE_SSSE3 | (USE_NEON >= 8))
146 static constexpr IndexType ChunkSize = 4;
148 static constexpr IndexType ChunkSize = 1;
151 using OutputBuffer = OutputType[PaddedOutputDimensions];
153 // Hash value embedded in the evaluation file
154 static constexpr std::uint32_t get_hash_value(std::uint32_t prevHash) {
155 std::uint32_t hashValue = 0xCC03DAE4u;
156 hashValue += OutputDimensions;
157 hashValue ^= prevHash >> 1;
158 hashValue ^= prevHash << 31;
162 static constexpr IndexType get_weight_index_scrambled(IndexType i)
165 (i / ChunkSize) % (PaddedInputDimensions / ChunkSize) * OutputDimensions * ChunkSize +
166 i / PaddedInputDimensions * ChunkSize +
170 static constexpr IndexType get_weight_index(IndexType i)
172 #if (USE_SSSE3 | (USE_NEON >= 8))
173 return get_weight_index_scrambled(i);
179 // Read network parameters
180 bool read_parameters(std::istream& stream) {
181 read_little_endian<BiasType>(stream, biases, OutputDimensions);
182 for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
183 weights[get_weight_index(i)] = read_little_endian<WeightType>(stream);
185 return !stream.fail();
188 // Write network parameters
189 bool write_parameters(std::ostream& stream) const {
190 write_little_endian<BiasType>(stream, biases, OutputDimensions);
192 for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
193 write_little_endian<WeightType>(stream, weights[get_weight_index(i)]);
195 return !stream.fail();
197 // Forward propagation
199 const InputType* input, OutputType* output) const {
201 #if (USE_SSSE3 | (USE_NEON >= 8))
202 #if defined (USE_AVX512)
203 using invec_t = __m512i;
204 using outvec_t = __m512i;
205 #define vec_set_32 _mm512_set1_epi32
206 #define vec_add_dpbusd_32 Simd::m512_add_dpbusd_epi32
207 #elif defined (USE_AVX2)
208 using invec_t = __m256i;
209 using outvec_t = __m256i;
210 #define vec_set_32 _mm256_set1_epi32
211 #define vec_add_dpbusd_32 Simd::m256_add_dpbusd_epi32
212 #elif defined (USE_SSSE3)
213 using invec_t = __m128i;
214 using outvec_t = __m128i;
215 #define vec_set_32 _mm_set1_epi32
216 #define vec_add_dpbusd_32 Simd::m128_add_dpbusd_epi32
217 #elif defined (USE_NEON_DOTPROD)
218 using invec_t = int8x16_t;
219 using outvec_t = int32x4_t;
220 #define vec_set_32(a) vreinterpretq_s8_u32(vdupq_n_u32(a))
221 #define vec_add_dpbusd_32 Simd::dotprod_m128_add_dpbusd_epi32
222 #elif defined (USE_NEON)
223 using invec_t = int8x16_t;
224 using outvec_t = int32x4_t;
225 #define vec_set_32(a) vreinterpretq_s8_u32(vdupq_n_u32(a))
226 #define vec_add_dpbusd_32 Simd::neon_m128_add_dpbusd_epi32
228 static constexpr IndexType OutputSimdWidth = sizeof(outvec_t) / sizeof(OutputType);
230 constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 8) / ChunkSize;
231 constexpr IndexType NumRegs = OutputDimensions / OutputSimdWidth;
232 std::uint16_t nnz[NumChunks];
235 const auto input32 = reinterpret_cast<const std::int32_t*>(input);
237 // Find indices of nonzero 32bit blocks
238 find_nnz<NumChunks>(input32, nnz, count);
240 const outvec_t* biasvec = reinterpret_cast<const outvec_t*>(biases);
241 outvec_t acc[NumRegs];
242 for (IndexType k = 0; k < NumRegs; ++k)
245 for (IndexType j = 0; j < count; ++j)
247 const auto i = nnz[j];
248 const invec_t in = vec_set_32(input32[i]);
249 const auto col = reinterpret_cast<const invec_t*>(&weights[i * OutputDimensions * ChunkSize]);
250 for (IndexType k = 0; k < NumRegs; ++k)
251 vec_add_dpbusd_32(acc[k], in, col[k]);
254 outvec_t* outptr = reinterpret_cast<outvec_t*>(output);
255 for (IndexType k = 0; k < NumRegs; ++k)
258 # undef vec_add_dpbusd_32
260 // Use dense implementation for the other architectures.
261 affine_transform_non_ssse3<
263 PaddedInputDimensions,
264 OutputDimensions>(output, weights, biases, input);
269 using BiasType = OutputType;
270 using WeightType = std::int8_t;
272 alignas(CacheLineSize) BiasType biases[OutputDimensions];
273 alignas(CacheLineSize) WeightType weights[OutputDimensions * PaddedInputDimensions];
276 } // namespace Stockfish::Eval::NNUE::Layers
278 #endif // #ifndef NNUE_LAYERS_AFFINE_TRANSFORM_SPARSE_INPUT_H_INCLUDED