]> git.sesse.net Git - stockfish/blob - src/nnue/layers/affine_transform_sparse_input.h
Simplify lookup_count and clean up pieces().
[stockfish] / src / nnue / layers / affine_transform_sparse_input.h
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2023 The Stockfish developers (see AUTHORS file)
4
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.
9
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.
14
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/>.
17 */
18
19 // Definition of layer AffineTransformSparseInput of NNUE evaluation function
20
21 #ifndef NNUE_LAYERS_AFFINE_TRANSFORM_SPARSE_INPUT_H_INCLUDED
22 #define NNUE_LAYERS_AFFINE_TRANSFORM_SPARSE_INPUT_H_INCLUDED
23
24 #include <iostream>
25 #include <algorithm>
26 #include <array>
27 #include <bitset>
28 #include <type_traits>
29 #include "../nnue_common.h"
30 #include "affine_transform.h"
31 #include "simd.h"
32
33 /*
34   This file contains the definition for a fully connected layer (aka affine transform) with block sparse input.
35 */
36
37 namespace Stockfish::Eval::NNUE::Layers {
38 #if defined(__GNUC__)  // GCC, Clang, ICC
39
40   static inline IndexType lsb_(std::uint32_t b) {
41     assert(b);
42     return IndexType(__builtin_ctzl(b));
43   }
44
45 #elif defined(_MSC_VER)  // MSVC
46
47   static inline IndexType lsb_(std::uint32_t b) {
48     assert(b);
49     unsigned long idx;
50     _BitScanForward(&idx, b);
51     return (IndexType) idx;
52   }
53
54 #else  // Compiler is neither GCC nor MSVC compatible
55
56 #error "Compiler not supported."
57
58 #endif
59
60
61 #if defined(USE_SSSE3)
62   alignas(CacheLineSize) static inline const std::array<std::array<std::uint16_t, 8>, 256> lookup_indices = [](){
63     std::array<std::array<std::uint16_t, 8>, 256> v{};
64     for (int i = 0; i < 256; ++i)
65     {
66       int j = i;
67       int k = 0;
68       while(j)
69       {
70         const IndexType lsbIndex = lsb_(std::uint32_t(j));
71         j &= j - 1;
72         v[i][k] = lsbIndex;
73         ++k;
74       }
75     }
76     return v;
77   }();
78   alignas(CacheLineSize) static inline const std::array<unsigned, 256> lookup_count = [](){
79     std::array<unsigned, 256> v;
80     for (int i = 0; i < 256; ++i)
81       v[i] = unsigned(std::bitset<8>(i).count());
82     return v;
83   }();
84
85   // Find indices of nonzero numbers in an int32_t array
86   template<const IndexType InputDimensions>
87   void find_nnz(const std::int32_t* input, std::uint16_t* out, IndexType& count_out) {
88 #if defined (USE_AVX512)
89     using vec_t = __m512i;
90     #define vec_nnz(a) _mm512_cmpgt_epi32_mask(a, _mm512_setzero_si512())
91 #elif defined (USE_AVX2)
92     using vec_t = __m256i;
93     #define vec_nnz(a) _mm256_movemask_ps(_mm256_castsi256_ps(_mm256_cmpgt_epi32(a, _mm256_setzero_si256())))
94 #elif defined (USE_SSSE3)
95     using vec_t = __m128i;
96     #define vec_nnz(a) _mm_movemask_ps(_mm_castsi128_ps(_mm_cmpgt_epi32(a, _mm_setzero_si128())))
97 #endif
98     constexpr IndexType InputSimdWidth = sizeof(vec_t) / sizeof(std::int32_t);
99     // Inputs are processed InputSimdWidth at a time and outputs are processed 8 at a time so we process in chunks of max(InputSimdWidth, 8)
100     constexpr IndexType ChunkSize = std::max<IndexType>(InputSimdWidth, 8);
101     constexpr IndexType NumChunks = InputDimensions / ChunkSize;
102     constexpr IndexType InputsPerChunk = ChunkSize / InputSimdWidth;
103     constexpr IndexType OutputsPerChunk = ChunkSize / 8;
104
105     const auto inputVector = reinterpret_cast<const vec_t*>(input);
106     IndexType count = 0;
107     __m128i base = _mm_set1_epi16(0);
108     __m128i increment = _mm_set1_epi16(8);
109     for (IndexType i = 0; i < NumChunks; ++i)
110     {
111       // bitmask of nonzero values in this chunk
112       unsigned nnz = 0;
113       for (IndexType j = 0; j < InputsPerChunk; ++j)
114       {
115         const vec_t inputChunk = inputVector[i * InputsPerChunk + j];
116         nnz |= (unsigned)vec_nnz(inputChunk) << (j * InputSimdWidth);
117       }
118       for (IndexType j = 0; j < OutputsPerChunk; ++j)
119       {
120         const auto lookup = (nnz >> (j * 8)) & 0xFF;
121         const auto offsets = _mm_loadu_si128(reinterpret_cast<const __m128i*>(&lookup_indices[lookup]));
122         _mm_storeu_si128(reinterpret_cast<__m128i*>(out + count), _mm_add_epi16(base, offsets));
123         count += lookup_count[lookup];
124         base = _mm_add_epi16(base, increment);
125       }
126     }
127     count_out = count;
128   }
129 # undef vec_nnz
130 #endif
131
132   // Sparse input implementation
133   template <IndexType InDims, IndexType OutDims>
134   class AffineTransformSparseInput {
135    public:
136     // Input/output type
137     // Input/output type
138     using InputType = std::uint8_t;
139     using OutputType = std::int32_t;
140
141     // Number of input/output dimensions
142     static constexpr IndexType InputDimensions = InDims;
143     static constexpr IndexType OutputDimensions = OutDims;
144
145     static_assert(OutputDimensions % 16 == 0, "Only implemented for OutputDimensions divisible by 16.");
146
147     static constexpr IndexType PaddedInputDimensions =
148       ceil_to_multiple<IndexType>(InputDimensions, MaxSimdWidth);
149     static constexpr IndexType PaddedOutputDimensions =
150       ceil_to_multiple<IndexType>(OutputDimensions, MaxSimdWidth);
151
152 #if defined (USE_SSSE3)
153     static constexpr IndexType ChunkSize = 4;
154 #else
155     static constexpr IndexType ChunkSize = 1;
156 #endif
157
158     using OutputBuffer = OutputType[PaddedOutputDimensions];
159
160     // Hash value embedded in the evaluation file
161     static constexpr std::uint32_t get_hash_value(std::uint32_t prevHash) {
162       std::uint32_t hashValue = 0xCC03DAE4u;
163       hashValue += OutputDimensions;
164       hashValue ^= prevHash >> 1;
165       hashValue ^= prevHash << 31;
166       return hashValue;
167     }
168
169     static IndexType get_weight_index_scrambled(IndexType i)
170     {
171       return
172         (i / ChunkSize) % (PaddedInputDimensions / ChunkSize) * OutputDimensions * ChunkSize +
173         i / PaddedInputDimensions * ChunkSize +
174         i % ChunkSize;
175     }
176
177     static IndexType get_weight_index(IndexType i)
178     {
179 #if defined (USE_SSSE3)
180       return get_weight_index_scrambled(i);
181 #else
182       return i;
183 #endif
184     }
185
186     // Read network parameters
187     bool read_parameters(std::istream& stream) {
188       read_little_endian<BiasType>(stream, biases, OutputDimensions);
189       for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
190         weights[get_weight_index(i)] = read_little_endian<WeightType>(stream);
191
192       return !stream.fail();
193     }
194
195     // Write network parameters
196     bool write_parameters(std::ostream& stream) const {
197       write_little_endian<BiasType>(stream, biases, OutputDimensions);
198
199       for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
200         write_little_endian<WeightType>(stream, weights[get_weight_index(i)]);
201
202       return !stream.fail();
203     }
204     // Forward propagation
205     const OutputType* propagate(
206         const InputType* input, OutputType* output) const {
207
208 #if defined (USE_SSSE3)
209 #if defined (USE_AVX512)
210       using vec_t = __m512i;
211       #define vec_setzero _mm512_setzero_si512
212       #define vec_set_32 _mm512_set1_epi32
213       #define vec_add_dpbusd_32 Simd::m512_add_dpbusd_epi32
214 #elif defined (USE_AVX2)
215       using vec_t = __m256i;
216       #define vec_setzero _mm256_setzero_si256
217       #define vec_set_32 _mm256_set1_epi32
218       #define vec_add_dpbusd_32 Simd::m256_add_dpbusd_epi32
219 #elif defined (USE_SSSE3)
220       using vec_t = __m128i;
221       #define vec_setzero _mm_setzero_si128
222       #define vec_set_32 _mm_set1_epi32
223       #define vec_add_dpbusd_32 Simd::m128_add_dpbusd_epi32
224 #endif
225       static constexpr IndexType OutputSimdWidth = sizeof(vec_t) / sizeof(OutputType);
226
227       constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 8) / ChunkSize;
228       constexpr IndexType NumRegs = OutputDimensions / OutputSimdWidth;
229       std::uint16_t nnz[NumChunks];
230       IndexType count;
231
232       const auto input32 = reinterpret_cast<const std::int32_t*>(input);
233
234       // Find indices of nonzero 32bit blocks
235       find_nnz<NumChunks>(input32, nnz, count);
236
237       const vec_t* biasvec = reinterpret_cast<const vec_t*>(biases);
238       vec_t acc[NumRegs];
239       for (IndexType k = 0; k < NumRegs; ++k)
240         acc[k] = biasvec[k];
241
242       for (IndexType j = 0; j < count; ++j)
243       {
244         const auto i = nnz[j];
245         const vec_t in = vec_set_32(input32[i]);
246         const auto col = reinterpret_cast<const vec_t*>(&weights[i * OutputDimensions * ChunkSize]);
247         for (IndexType k = 0; k < NumRegs; ++k)
248           vec_add_dpbusd_32(acc[k], in, col[k]);
249       }
250
251       vec_t* outptr = reinterpret_cast<vec_t*>(output);
252       for (IndexType k = 0; k < NumRegs; ++k)
253         outptr[k] = acc[k];
254 # undef vec_setzero
255 # undef vec_set_32
256 # undef vec_add_dpbusd_32
257 #else
258       // Use dense implementation for the other architectures.
259       affine_transform_non_ssse3<
260         InputDimensions,
261         PaddedInputDimensions,
262         OutputDimensions>(output, weights, biases, input);
263 #endif
264
265       return output;
266     }
267
268    private:
269     using BiasType = OutputType;
270     using WeightType = std::int8_t;
271
272     alignas(CacheLineSize) BiasType biases[OutputDimensions];
273     alignas(CacheLineSize) WeightType weights[OutputDimensions * PaddedInputDimensions];
274   };
275
276 }  // namespace Stockfish::Eval::NNUE::Layers
277
278 #endif // #ifndef NNUE_LAYERS_AFFINE_TRANSFORM_SPARSE_INPUT_H_INCLUDED