]> git.sesse.net Git - stockfish/blob - src/nnue/layers/affine_transform_sparse_input.h
a5bea08e74b3fbaea0431a5daf2329d83288e605
[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
38 #if defined(USE_SSSE3)
39   alignas(CacheLineSize) static inline const std::array<std::array<std::uint16_t, 8>, 256> lookup_indices = [](){
40     std::array<std::array<std::uint16_t, 8>, 256> v{};
41     for (unsigned i = 0; i < 256; ++i)
42     {
43       std::uint64_t j = i, k = 0;
44       while(j)
45         v[i][k++] = pop_lsb(j);
46     }
47     return v;
48   }();
49
50   // Find indices of nonzero numbers in an int32_t array
51   template<const IndexType InputDimensions>
52   void find_nnz(const std::int32_t* input, std::uint16_t* out, IndexType& count_out) {
53 #if defined (USE_AVX512)
54     using vec_t = __m512i;
55     #define vec_nnz(a) _mm512_cmpgt_epi32_mask(a, _mm512_setzero_si512())
56 #elif defined (USE_AVX2)
57     using vec_t = __m256i;
58     #if defined(USE_VNNI) && !defined(USE_AVXVNNI)
59         #define vec_nnz(a) _mm256_cmpgt_epi32_mask(a, _mm256_setzero_si256())
60     #else
61         #define vec_nnz(a) _mm256_movemask_ps(_mm256_castsi256_ps(_mm256_cmpgt_epi32(a, _mm256_setzero_si256())))
62     #endif
63 #elif defined (USE_SSSE3)
64     using vec_t = __m128i;
65     #define vec_nnz(a) _mm_movemask_ps(_mm_castsi128_ps(_mm_cmpgt_epi32(a, _mm_setzero_si128())))
66 #endif
67     constexpr IndexType InputSimdWidth = sizeof(vec_t) / sizeof(std::int32_t);
68     // Inputs are processed InputSimdWidth at a time and outputs are processed 8 at a time so we process in chunks of max(InputSimdWidth, 8)
69     constexpr IndexType ChunkSize = std::max<IndexType>(InputSimdWidth, 8);
70     constexpr IndexType NumChunks = InputDimensions / ChunkSize;
71     constexpr IndexType InputsPerChunk = ChunkSize / InputSimdWidth;
72     constexpr IndexType OutputsPerChunk = ChunkSize / 8;
73
74     const auto inputVector = reinterpret_cast<const vec_t*>(input);
75     IndexType count = 0;
76     __m128i base = _mm_setzero_si128();
77     const __m128i increment = _mm_set1_epi16(8);
78     for (IndexType i = 0; i < NumChunks; ++i)
79     {
80       // bitmask of nonzero values in this chunk
81       unsigned nnz = 0;
82       for (IndexType j = 0; j < InputsPerChunk; ++j)
83       {
84         const vec_t inputChunk = inputVector[i * InputsPerChunk + j];
85         nnz |= (unsigned)vec_nnz(inputChunk) << (j * InputSimdWidth);
86       }
87       for (IndexType j = 0; j < OutputsPerChunk; ++j)
88       {
89         const auto lookup = (nnz >> (j * 8)) & 0xFF;
90         const auto offsets = _mm_loadu_si128(reinterpret_cast<const __m128i*>(&lookup_indices[lookup]));
91         _mm_storeu_si128(reinterpret_cast<__m128i*>(out + count), _mm_add_epi16(base, offsets));
92         count += popcount(lookup);
93         base = _mm_add_epi16(base, increment);
94       }
95     }
96     count_out = count;
97   }
98 # undef vec_nnz
99 #endif
100
101   // Sparse input implementation
102   template <IndexType InDims, IndexType OutDims>
103   class AffineTransformSparseInput {
104    public:
105     // Input/output type
106     // Input/output type
107     using InputType = std::uint8_t;
108     using OutputType = std::int32_t;
109
110     // Number of input/output dimensions
111     static constexpr IndexType InputDimensions = InDims;
112     static constexpr IndexType OutputDimensions = OutDims;
113
114     static_assert(OutputDimensions % 16 == 0, "Only implemented for OutputDimensions divisible by 16.");
115
116     static constexpr IndexType PaddedInputDimensions =
117       ceil_to_multiple<IndexType>(InputDimensions, MaxSimdWidth);
118     static constexpr IndexType PaddedOutputDimensions =
119       ceil_to_multiple<IndexType>(OutputDimensions, MaxSimdWidth);
120
121 #if defined (USE_SSSE3)
122     static constexpr IndexType ChunkSize = 4;
123 #else
124     static constexpr IndexType ChunkSize = 1;
125 #endif
126
127     using OutputBuffer = OutputType[PaddedOutputDimensions];
128
129     // Hash value embedded in the evaluation file
130     static constexpr std::uint32_t get_hash_value(std::uint32_t prevHash) {
131       std::uint32_t hashValue = 0xCC03DAE4u;
132       hashValue += OutputDimensions;
133       hashValue ^= prevHash >> 1;
134       hashValue ^= prevHash << 31;
135       return hashValue;
136     }
137
138     static IndexType get_weight_index_scrambled(IndexType i)
139     {
140       return
141         (i / ChunkSize) % (PaddedInputDimensions / ChunkSize) * OutputDimensions * ChunkSize +
142         i / PaddedInputDimensions * ChunkSize +
143         i % ChunkSize;
144     }
145
146     static IndexType get_weight_index(IndexType i)
147     {
148 #if defined (USE_SSSE3)
149       return get_weight_index_scrambled(i);
150 #else
151       return i;
152 #endif
153     }
154
155     // Read network parameters
156     bool read_parameters(std::istream& stream) {
157       read_little_endian<BiasType>(stream, biases, OutputDimensions);
158       for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
159         weights[get_weight_index(i)] = read_little_endian<WeightType>(stream);
160
161       return !stream.fail();
162     }
163
164     // Write network parameters
165     bool write_parameters(std::ostream& stream) const {
166       write_little_endian<BiasType>(stream, biases, OutputDimensions);
167
168       for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
169         write_little_endian<WeightType>(stream, weights[get_weight_index(i)]);
170
171       return !stream.fail();
172     }
173     // Forward propagation
174     const OutputType* propagate(
175         const InputType* input, OutputType* output) const {
176
177 #if defined (USE_SSSE3)
178 #if defined (USE_AVX512)
179       using vec_t = __m512i;
180       #define vec_setzero _mm512_setzero_si512
181       #define vec_set_32 _mm512_set1_epi32
182       #define vec_add_dpbusd_32 Simd::m512_add_dpbusd_epi32
183 #elif defined (USE_AVX2)
184       using vec_t = __m256i;
185       #define vec_setzero _mm256_setzero_si256
186       #define vec_set_32 _mm256_set1_epi32
187       #define vec_add_dpbusd_32 Simd::m256_add_dpbusd_epi32
188 #elif defined (USE_SSSE3)
189       using vec_t = __m128i;
190       #define vec_setzero _mm_setzero_si128
191       #define vec_set_32 _mm_set1_epi32
192       #define vec_add_dpbusd_32 Simd::m128_add_dpbusd_epi32
193 #endif
194       static constexpr IndexType OutputSimdWidth = sizeof(vec_t) / sizeof(OutputType);
195
196       constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 8) / ChunkSize;
197       constexpr IndexType NumRegs = OutputDimensions / OutputSimdWidth;
198       std::uint16_t nnz[NumChunks];
199       IndexType count;
200
201       const auto input32 = reinterpret_cast<const std::int32_t*>(input);
202
203       // Find indices of nonzero 32bit blocks
204       find_nnz<NumChunks>(input32, nnz, count);
205
206       const vec_t* biasvec = reinterpret_cast<const vec_t*>(biases);
207       vec_t acc[NumRegs];
208       for (IndexType k = 0; k < NumRegs; ++k)
209         acc[k] = biasvec[k];
210
211       for (IndexType j = 0; j < count; ++j)
212       {
213         const auto i = nnz[j];
214         const vec_t in = vec_set_32(input32[i]);
215         const auto col = reinterpret_cast<const vec_t*>(&weights[i * OutputDimensions * ChunkSize]);
216         for (IndexType k = 0; k < NumRegs; ++k)
217           vec_add_dpbusd_32(acc[k], in, col[k]);
218       }
219
220       vec_t* outptr = reinterpret_cast<vec_t*>(output);
221       for (IndexType k = 0; k < NumRegs; ++k)
222         outptr[k] = acc[k];
223 # undef vec_setzero
224 # undef vec_set_32
225 # undef vec_add_dpbusd_32
226 #else
227       // Use dense implementation for the other architectures.
228       affine_transform_non_ssse3<
229         InputDimensions,
230         PaddedInputDimensions,
231         OutputDimensions>(output, weights, biases, input);
232 #endif
233
234       return output;
235     }
236
237    private:
238     using BiasType = OutputType;
239     using WeightType = std::int8_t;
240
241     alignas(CacheLineSize) BiasType biases[OutputDimensions];
242     alignas(CacheLineSize) WeightType weights[OutputDimensions * PaddedInputDimensions];
243   };
244
245 }  // namespace Stockfish::Eval::NNUE::Layers
246
247 #endif // #ifndef NNUE_LAYERS_AFFINE_TRANSFORM_SPARSE_INPUT_H_INCLUDED