Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
/*++
 
Copyright (c) Microsoft Corporation. All rights reserved.
 
Licensed under the MIT License.
 
Module Name:
 
    layernorm_kernel_avx2.cpp
 
Abstract:
 
    This module implements LayerNorm/RMSNorm kernels using x86 AVX2+FMA3
    intrinsics. Processes one normalization row at a time, matching the
    MLAS_LAYERNORM_F32_KERNEL signature dispatched from platform.cpp.
 
    RMSNorm uses a vectorised sum-of-squares accumulation (two-pass:
    reduce then normalise), processing 8 floats per iteration.
 
    Full LayerNorm uses a centered two-pass algorithm:
      Pass 1 — compute the mean via a double-precision sum (4 doubles
               per AVX2 iteration using vcvtps2pd + vaddpd). This keeps
               rounding in the mean from corrupting the centered variance
               for large-magnitude inputs.
      Pass 2 — accumulate sum((x - mean)^2) in fp32 (8 floats per
               iteration). Subtracting the (accurate) mean before
               squaring eliminates the catastrophic cancellation that
               plagues the uncentered E[x^2]-mean^2 formulation.
 
    A scalar tail handles lengths that are not a multiple of 8 (or 4
    for the double-precision mean pass).
 
--*/
 
#include "mlasi.h"
#include "mlas_float16.h"
 
#if defined(MLAS_TARGET_AMD64) || defined(MLAS_TARGET_IX86)
 
#include <immintrin.h>
 
#include <cassert>
#include <cmath>
 
void MLASCALL
MlasLayerNormKernelAvx2(
    const float* Input,
    const float* Scale,
    const float* Bias,
    float* Output,
    float* MeanOut,
    float* InvStdDevOut,
    size_t NormSize,
    float Epsilon,
    bool Simplified)
{
    assert(!Simplified || Bias == nullptr);
 
    const size_t n = NormSize;
 
    float mean_val;
    float inv_denom;
 
    if (Simplified) {
        //
        // RMSNorm: accumulate sum-of-squares for the inverse RMS
        // denominator. The mean is only needed when the caller requests
        // MeanOut — the normalisation itself never subtracts the mean.
        // Skip the sum accumulation when MeanOut is null to avoid ~1
        // extra vaddps per 8-element iteration.
        //
 
        __m256 vsumsq = _mm256_setzero_ps();
        size_t i = 0;
        float sumsq_val;
 
        if (MeanOut != nullptr) {
            //
            // Caller wants the mean: accumulate sum in double precision
            // alongside sum-of-squares in fp32.
            //
            __m256d vsumd = _mm256_setzero_pd();
            for (; i + 8 <= n; i += 8) {
                __m256 vx = _mm256_loadu_ps(Input + i);
                __m128 vx_lo = _mm256_castps256_ps128(vx);
                __m128 vx_hi = _mm256_extractf128_ps(vx, 1);
                vsumd = _mm256_add_pd(vsumd, _mm256_cvtps_pd(vx_lo));
                vsumd = _mm256_add_pd(vsumd, _mm256_cvtps_pd(vx_hi));
                vsumsq = _mm256_fmadd_ps(vx, vx, vsumsq);
            }
 
            // Horizontal reduce double sum.
            __m128d hi_d = _mm256_extractf128_pd(vsumd, 1);
            __m128d lo_d = _mm256_castpd256_pd128(vsumd);
            __m128d rd = _mm_add_pd(lo_d, hi_d);
            rd = _mm_add_sd(rd, _mm_unpackhi_pd(rd, rd));
            double dsum = _mm_cvtsd_f64(rd);
 
            // Horizontal reduce sum-of-squares.
            __m128 hi_sq = _mm256_extractf128_ps(vsumsq, 1);
            __m128 lo_sq = _mm256_castps256_ps128(vsumsq);
            __m128 r_sq = _mm_add_ps(lo_sq, hi_sq);
            r_sq = _mm_add_ps(r_sq, _mm_movehl_ps(r_sq, r_sq));
            r_sq = _mm_add_ss(r_sq, _mm_movehdup_ps(r_sq));
            sumsq_val = _mm_cvtss_f32(r_sq);
 
            for (; i < n; i++) {
                dsum += static_cast<double>(Input[i]);
                sumsq_val += Input[i] * Input[i];
            }
 
            mean_val = static_cast<float>(dsum / static_cast<double>(n));
        } else {
            //
            // No mean requested: sum-of-squares only.
            //
            for (; i + 8 <= n; i += 8) {
                __m256 vx = _mm256_loadu_ps(Input + i);
                vsumsq = _mm256_fmadd_ps(vx, vx, vsumsq);
            }
 
            // Horizontal reduce sum-of-squares.
            __m128 hi_sq = _mm256_extractf128_ps(vsumsq, 1);
            __m128 lo_sq = _mm256_castps256_ps128(vsumsq);
            __m128 r_sq = _mm_add_ps(lo_sq, hi_sq);
            r_sq = _mm_add_ps(r_sq, _mm_movehl_ps(r_sq, r_sq));
            r_sq = _mm_add_ss(r_sq, _mm_movehdup_ps(r_sq));
            sumsq_val = _mm_cvtss_f32(r_sq);
 
            for (; i < n; i++) {
                sumsq_val += Input[i] * Input[i];
            }
 
            mean_val = 0.0f;
        }
 
        inv_denom = 1.0f / sqrtf(sumsq_val / static_cast<float>(n) + Epsilon);
    } else {
        //
        // Full LayerNorm: centered two-pass algorithm.
        //
        // Pass 1 — Compute the mean using double-precision accumulation.
        // This prevents fp32 summation error for large-magnitude inputs
        // from corrupting the centered variance in the second pass.
        //
 
        __m256d vsumd = _mm256_setzero_pd();
        size_t i = 0;
        for (; i + 4 <= n; i += 4) {
            __m128 vf = _mm_loadu_ps(Input + i);
            vsumd = _mm256_add_pd(vsumd, _mm256_cvtps_pd(vf));
        }
 
        // Horizontal reduce the 4 double lanes.
        __m128d hi_d = _mm256_extractf128_pd(vsumd, 1);
        __m128d lo_d = _mm256_castpd256_pd128(vsumd);
        __m128d rd = _mm_add_pd(lo_d, hi_d);
        rd = _mm_add_sd(rd, _mm_unpackhi_pd(rd, rd));
        double dsum = _mm_cvtsd_f64(rd);
 
        for (; i < n; i++) {
            dsum += static_cast<double>(Input[i]);
        }
 
        mean_val = static_cast<float>(dsum / static_cast<double>(n));
 
        //
        // Pass 2 — Accumulate centered sum-of-squared-deviations in fp32.
        // Subtracting the (accurate) mean before squaring removes the
        // catastrophic cancellation that plagues E[x^2] - mean^2.
        //
 
        __m256 vmean_acc = _mm256_set1_ps(mean_val);
        __m256 vvar = _mm256_setzero_ps();
        i = 0;
        for (; i + 8 <= n; i += 8) {
            __m256 vd = _mm256_sub_ps(_mm256_loadu_ps(Input + i), vmean_acc);
            vvar = _mm256_fmadd_ps(vd, vd, vvar);
        }
 
        // Horizontal reduce.
        __m128 hi = _mm256_extractf128_ps(vvar, 1);
        __m128 lo = _mm256_castps256_ps128(vvar);
        __m128 r = _mm_add_ps(lo, hi);
        r = _mm_add_ps(r, _mm_movehl_ps(r, r));
        r = _mm_add_ss(r, _mm_movehdup_ps(r));
        float var_val = _mm_cvtss_f32(r);
 
        for (; i < n; i++) {
            float d = Input[i] - mean_val;
            var_val += d * d;
        }
 
        inv_denom = 1.0f / sqrtf(var_val / static_cast<float>(n) + Epsilon);
    }
 
    //
    // Pass 2: Normalise and write output.
    //
 
    __m256 vmean = _mm256_set1_ps(mean_val);
    __m256 vinv = _mm256_set1_ps(inv_denom);
 
    size_t i = 0;
    if (Simplified) {
        for (; i + 8 <= n; i += 8) {
            __m256 vx = _mm256_loadu_ps(Input + i);
            __m256 vs = _mm256_loadu_ps(Scale + i);
            __m256 vy = _mm256_mul_ps(vx, vinv);
            vy = _mm256_mul_ps(vy, vs);
            _mm256_storeu_ps(Output + i, vy);
        }
        for (; i < n; i++) {
            Output[i] = Input[i] * inv_denom * Scale[i];
        }
    } else if (Bias == nullptr) {
        for (; i + 8 <= n; i += 8) {
            __m256 vx = _mm256_loadu_ps(Input + i);
            __m256 vs = _mm256_loadu_ps(Scale + i);
            __m256 vy = _mm256_sub_ps(vx, vmean);
            vy = _mm256_mul_ps(vy, vinv);
            vy = _mm256_mul_ps(vy, vs);
            _mm256_storeu_ps(Output + i, vy);
        }
        for (; i < n; i++) {
            Output[i] = (Input[i] - mean_val) * inv_denom * Scale[i];
        }
    } else {
        for (; i + 8 <= n; i += 8) {
            __m256 vx = _mm256_loadu_ps(Input + i);
            __m256 vs = _mm256_loadu_ps(Scale + i);
            __m256 vb = _mm256_loadu_ps(Bias + i);
            __m256 vy = _mm256_sub_ps(vx, vmean);
            vy = _mm256_mul_ps(vy, vinv);
            vy = _mm256_fmadd_ps(vy, vs, vb);
            _mm256_storeu_ps(Output + i, vy);
        }
        for (; i < n; i++) {
            Output[i] = (Input[i] - mean_val) * inv_denom * Scale[i] + Bias[i];
        }
    }
 
    if (MeanOut != nullptr) {
        *MeanOut = mean_val;
    }
    if (InvStdDevOut != nullptr) {
        *InvStdDevOut = inv_denom;
    }
}
 
void MLASCALL
MlasLayerNormKernelF16Avx2(
    const uint16_t* Input,
    const float* Scale,
    const float* Bias,
    uint16_t* Output,
    float* MeanOut,
    float* InvStdDevOut,
    size_t NormSize,
    float Epsilon,
    bool Simplified)
{
    assert(!Simplified || Bias == nullptr);
 
    const size_t n = NormSize;
    float mean_val = 0.0f;
    float inv_denom;
 
    if (Simplified) {
        __m256 vsumsq = _mm256_setzero_ps();
        size_t i = 0;
        double sum = 0.0;
        if (MeanOut != nullptr) {
            __m256d vsum = _mm256_setzero_pd();
            for (; i + 8 <= n; i += 8) {
                const __m256 vx = _mm256_cvtph_ps(
                    _mm_loadu_si128(reinterpret_cast<const __m128i*>(Input + i)));
                vsumsq = _mm256_fmadd_ps(vx, vx, vsumsq);
                vsum = _mm256_add_pd(vsum, _mm256_cvtps_pd(_mm256_castps256_ps128(vx)));
                vsum = _mm256_add_pd(vsum, _mm256_cvtps_pd(_mm256_extractf128_ps(vx, 1)));
            }
 
            __m128d rd = _mm_add_pd(
                _mm256_castpd256_pd128(vsum),
                _mm256_extractf128_pd(vsum, 1));
            rd = _mm_add_sd(rd, _mm_unpackhi_pd(rd, rd));
            sum = _mm_cvtsd_f64(rd);
        } else {
            for (; i + 8 <= n; i += 8) {
                const __m256 vx = _mm256_cvtph_ps(
                    _mm_loadu_si128(reinterpret_cast<const __m128i*>(Input + i)));
                vsumsq = _mm256_fmadd_ps(vx, vx, vsumsq);
            }
        }
 
        __m128 r = _mm_add_ps(
            _mm256_castps256_ps128(vsumsq),
            _mm256_extractf128_ps(vsumsq, 1));
        r = _mm_add_ps(r, _mm_movehl_ps(r, r));
        r = _mm_add_ss(r, _mm_movehdup_ps(r));
        float sumsq = _mm_cvtss_f32(r);
 
        for (; i < n; ++i) {
            const float value = MLAS_Half2Float(Input[i]);
            sumsq += value * value;
            if (MeanOut != nullptr) {
                sum += static_cast<double>(value);
            }
        }
 
        if (MeanOut != nullptr) {
            mean_val = static_cast<float>(sum / static_cast<double>(n));
        }
        inv_denom = 1.0f / sqrtf(sumsq / static_cast<float>(n) + Epsilon);
    } else {
        __m256d vsum = _mm256_setzero_pd();
        size_t i = 0;
        for (; i + 8 <= n; i += 8) {
            const __m256 vx = _mm256_cvtph_ps(
                _mm_loadu_si128(reinterpret_cast<const __m128i*>(Input + i)));
            vsum = _mm256_add_pd(vsum, _mm256_cvtps_pd(_mm256_castps256_ps128(vx)));
            vsum = _mm256_add_pd(vsum, _mm256_cvtps_pd(_mm256_extractf128_ps(vx, 1)));
        }
 
        __m128d rd = _mm_add_pd(
            _mm256_castpd256_pd128(vsum),
            _mm256_extractf128_pd(vsum, 1));
        rd = _mm_add_sd(rd, _mm_unpackhi_pd(rd, rd));
        double sum = _mm_cvtsd_f64(rd);
 
        for (; i < n; ++i) {
            sum += static_cast<double>(MLAS_Half2Float(Input[i]));
        }
 
        mean_val = static_cast<float>(sum / static_cast<double>(n));
        const __m256 vmean = _mm256_set1_ps(mean_val);
        __m256 vvariance = _mm256_setzero_ps();
        i = 0;
        for (; i + 8 <= n; i += 8) {
            const __m256 vx = _mm256_cvtph_ps(
                _mm_loadu_si128(reinterpret_cast<const __m128i*>(Input + i)));
            const __m256 vd = _mm256_sub_ps(vx, vmean);
            vvariance = _mm256_fmadd_ps(vd, vd, vvariance);
        }
 
        __m128 r = _mm_add_ps(
            _mm256_castps256_ps128(vvariance),
            _mm256_extractf128_ps(vvariance, 1));
        r = _mm_add_ps(r, _mm_movehl_ps(r, r));
        r = _mm_add_ss(r, _mm_movehdup_ps(r));
        float variance = _mm_cvtss_f32(r);
 
        for (; i < n; ++i) {
            const float delta = MLAS_Half2Float(Input[i]) - mean_val;
            variance += delta * delta;
        }
 
        inv_denom = 1.0f / sqrtf(variance / static_cast<float>(n) + Epsilon);
    }
 
    const __m256 vmean = _mm256_set1_ps(mean_val);
    const __m256 vinv = _mm256_set1_ps(inv_denom);
    size_t i = 0;
 
    if (Simplified) {
        for (; i + 8 <= n; i += 8) {
            const __m256 vx = _mm256_cvtph_ps(
                _mm_loadu_si128(reinterpret_cast<const __m128i*>(Input + i)));
            const __m256 vs = _mm256_loadu_ps(Scale + i);
            const __m256 vy = _mm256_mul_ps(_mm256_mul_ps(vx, vinv), vs);
            const __m128i half = _mm256_cvtps_ph(vy, _MM_FROUND_TO_NEAREST_INT);
            _mm_storeu_si128(reinterpret_cast<__m128i*>(Output + i), half);
        }
        for (; i < n; ++i) {
            Output[i] = MLAS_Float2Half(MLAS_Half2Float(Input[i]) * inv_denom * Scale[i]);
        }
    } else if (Bias == nullptr) {
        for (; i + 8 <= n; i += 8) {
            const __m256 vx = _mm256_cvtph_ps(
                _mm_loadu_si128(reinterpret_cast<const __m128i*>(Input + i)));
            const __m256 vs = _mm256_loadu_ps(Scale + i);
            const __m256 vy = _mm256_mul_ps(_mm256_mul_ps(_mm256_sub_ps(vx, vmean), vinv), vs);
            const __m128i half = _mm256_cvtps_ph(vy, _MM_FROUND_TO_NEAREST_INT);
            _mm_storeu_si128(reinterpret_cast<__m128i*>(Output + i), half);
        }
        for (; i < n; ++i) {
            Output[i] = MLAS_Float2Half(
                (MLAS_Half2Float(Input[i]) - mean_val) * inv_denom * Scale[i]);
        }
    } else {
        for (; i + 8 <= n; i += 8) {
            const __m256 vx = _mm256_cvtph_ps(
                _mm_loadu_si128(reinterpret_cast<const __m128i*>(Input + i)));
            const __m256 vs = _mm256_loadu_ps(Scale + i);
            const __m256 vb = _mm256_loadu_ps(Bias + i);
            const __m256 normalized = _mm256_mul_ps(_mm256_sub_ps(vx, vmean), vinv);
            const __m256 vy = _mm256_fmadd_ps(normalized, vs, vb);
            const __m128i half = _mm256_cvtps_ph(vy, _MM_FROUND_TO_NEAREST_INT);
            _mm_storeu_si128(reinterpret_cast<__m128i*>(Output + i), half);
        }
        for (; i < n; ++i) {
            Output[i] = MLAS_Float2Half(
                (MLAS_Half2Float(Input[i]) - mean_val) * inv_denom * Scale[i] + Bias[i]);
        }
    }
 
    if (MeanOut != nullptr) {
        *MeanOut = mean_val;
    }
    if (InvStdDevOut != nullptr) {
        *InvStdDevOut = inv_denom;
    }
}
 
#endif  // MLAS_TARGET_AMD64 || MLAS_TARGET_IX86