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