| 1 |
// Auto-generated file. Do not edit! |
| 2 |
// Template: src/f32-vrsqrt/rvv.c.in |
| 3 |
// Generator: tools/xngen |
| 4 |
// |
| 5 |
// Copyright 2024 Imagination Technologies, inc. |
| 6 |
// |
| 7 |
// This source code is licensed under the BSD-style license found in the |
| 8 |
// LICENSE file in the root directory of this source tree. |
| 9 |
|
| 10 |
#include <assert.h> |
| 11 |
|
| 12 |
#include <riscv_vector.h> |
| 13 |
|
| 14 |
#include "xnnpack/common.h" |
| 15 |
#include "xnnpack/vunary.h" |
| 16 |
|
| 17 |
// In the following, we do a single Newton-Raphson step on the equation |
| 18 |
// $x^{-2} - a$, which expands to: |
| 19 |
// |
| 20 |
// $$x_{k+1} = 0.5 * x_k * (3.0 - a * x_k^2)$$ |
| 21 |
// |
| 22 |
// So we do the following steps: |
| 23 |
// |
| 24 |
// 1. t0 = x_k |
| 25 |
// 2. t1 = t0 * t0 (x_k^2) |
| 26 |
// 3. t2 = a * t1 (a * x_k^2) |
| 27 |
// 4. t3 = 3.0 - t2 (3.0 - a * x_k^2) |
| 28 |
// 5. t4 = 0.5 * t0 (0.5 * x_k) |
| 29 |
// 6. y = t3 * t4 (0.5 * x_k * (3.0 - a * x_k^2)) |
| 30 |
// |
| 31 |
// Where $x_k$ is the original approximation and `y` contains the improved |
| 32 |
// approximation $x_{k+1}$. |
| 33 |
// |
| 34 |
// Note also that the initial approximation computed by the `vfrsqrt7` |
| 35 |
// instruction is only accurate to 7 bits (as opposed to 12 or 14 for x86_64), |
| 36 |
// which requires us to do two steps of the above. |
| 37 |
|
| 38 |
void xnn_f32_vrsqrt_ukernel__rvv_rsqrt_u2v( |
| 39 |
size_t batch, |
| 40 |
const float* input, |
| 41 |
float* output, |
| 42 |
const struct xnn_f32_default_params params[restrict XNN_MIN_ELEMENTS(1)]) XNN_OOB_READS |
| 43 |
{ |
| 44 |
assert(batch != 0); |
| 45 |
assert(batch % sizeof(float) == 0); |
| 46 |
assert(input != NULL); |
| 47 |
assert(output != NULL); |
| 48 |
|
| 49 |
batch >>= XNN_LOG2_SIZEOF_FLOAT; |
| 50 |
|
| 51 |
vfloat32m2_t onephalf_f32v = __riscv_vfmv_v_f_f32m2(1.5f, __riscv_vsetvl_e32m2(batch)); |
| 52 |
for (; batch > 0; ) { |
| 53 |
int32_t n = __riscv_vsetvl_e32m2(batch); batch -= n; |
| 54 |
vfloat32m2_t in_f32v = __riscv_vle32_v_f32m2(input, n); input += n; |
| 55 |
|
| 56 |
vfloat32m2_t t0_f32v = __riscv_vfrsqrt7_v_f32m2(in_f32v, n); |
| 57 |
vfloat32m2_t in_half_f32v = __riscv_vfmul_vf_f32m2(in_f32v, 0.5f, n); |
| 58 |
|
| 59 |
// First Newton-Raphson iteration |
| 60 |
vfloat32m2_t t1_f32v = __riscv_vfmul_vv_f32m2(t0_f32v, t0_f32v, n); |
| 61 |
vfloat32m2_t t2_f32v = __riscv_vfnmsub_vv_f32m2(in_half_f32v, t1_f32v, onephalf_f32v, n); |
| 62 |
t0_f32v = __riscv_vfmul_vv_f32m2(t0_f32v, t2_f32v, n); |
| 63 |
|
| 64 |
// Second Newton-Raphson iteration |
| 65 |
t1_f32v = __riscv_vfmul_vv_f32m2(t0_f32v, t0_f32v, n); |
| 66 |
t2_f32v = __riscv_vfnmsub_vv_f32m2(in_half_f32v, t1_f32v, onephalf_f32v, n); |
| 67 |
vfloat32m2_t y_f32v = __riscv_vfmul_vv_f32m2(t0_f32v, t2_f32v, n); |
| 68 |
|
| 69 |
__riscv_vse32_v_f32m2(output, y_f32v, n); output += n; |
| 70 |
} |
| 71 |
} |