|
| 1 | +#include <torch/all.h> |
| 2 | + |
| 3 | +#ifdef __SSE__ |
| 4 | +#include <xmmintrin.h> |
| 5 | +#endif |
| 6 | + |
| 7 | +#ifdef __ARM_NEON |
| 8 | +#include <arm_neon.h> |
| 9 | +#endif |
| 10 | + |
| 11 | +#ifdef __SSE__ |
| 12 | +void relu_forward_sse(float* out, const float* input, size_t size) { |
| 13 | + size_t i = 0; |
| 14 | + |
| 15 | + for (; i + 4 <= size; i += 4) { |
| 16 | + __m128 vec_input = _mm_load_ps(input + i); |
| 17 | + __m128 vec_zero = _mm_setzero_ps(); |
| 18 | + __m128 vec_output = _mm_max_ps(vec_input, vec_zero); |
| 19 | + _mm_store_ps(out + i, vec_output); |
| 20 | + } |
| 21 | + |
| 22 | + for (; i < size; ++i) { |
| 23 | + out[i] = input[i] > 0 ? input[i] : 0; |
| 24 | + } |
| 25 | +} |
| 26 | +#endif |
| 27 | + |
| 28 | +#ifdef __ARM_NEON |
| 29 | +void relu_forward_neon(float* out, const float* input, size_t size) { |
| 30 | + size_t i = 0; |
| 31 | + |
| 32 | + for (; i + 4 <= size; i += 4) { |
| 33 | + float32x4_t vec_input = vld1q_f32(input + i); |
| 34 | + float32x4_t vec_output = vmaxq_f32(vec_input, vdupq_n_f32(0)); |
| 35 | + vst1q_f32(out + i, vec_output); |
| 36 | + } |
| 37 | + |
| 38 | + for (; i < size; ++i) { |
| 39 | + out[i] = input[i] > 0 ? input[i] : 0; |
| 40 | + } |
| 41 | +} |
| 42 | +#endif |
| 43 | + |
| 44 | +void relu(torch::Tensor &out, torch::Tensor const &input) { |
| 45 | + TORCH_CHECK(out.dtype() == torch::kFloat32, "Output tensor must be of dtype float"); |
| 46 | + TORCH_CHECK(input.dtype() == torch::kFloat32, "Input tensor must be of dtype float"); |
| 47 | + TORCH_CHECK(out.numel() == input.numel(), "Input and output tensors must have the same number of elements"); |
| 48 | + |
| 49 | +#if defined(__SSE__) |
| 50 | + relu_forward_sse(out.data_ptr<float>(), input.data_ptr<float>(), input.numel()); |
| 51 | +#elif defined(__ARM_NEON) |
| 52 | + relu_forward_neon(out.data_ptr<float>(), input.data_ptr<float>(), input.numel()); |
| 53 | +#else |
| 54 | + #error "Unsupported architecture; please use a CPU with SSE or ARM NEON support." |
| 55 | +#endif |
| 56 | +} |
0 commit comments