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