| 49 | |
| 50 | template <typename T> |
| 51 | SimpleTensor<T> l2_normalize(const SimpleTensor<T> &src, unsigned int axis, float epsilon) |
| 52 | { |
| 53 | // Create reference |
| 54 | SimpleTensor<T> dst{src.shape(), src.data_type()}; |
| 55 | |
| 56 | // Reduce across given axis |
| 57 | SimpleTensor<T> sum = |
| 58 | reduction_operation<T, T>(src, get_output_shape(src.shape(), axis), axis, ReductionOperation::SUM_SQUARE); |
| 59 | |
| 60 | // Compute reference |
| 61 | const int upper_dims = src.shape().total_size_upper(axis + 1); |
| 62 | const int lower_dims = src.shape().total_size_lower(axis + 1); |
| 63 | const int lower_dims_sum = sum.shape().total_size_lower(axis + 1); |
| 64 | |
| 65 | for (int du = 0; du < upper_dims; ++du) |
| 66 | { |
| 67 | const T *src_row_ptr = src.data() + du * lower_dims; |
| 68 | T *dst_row_ptr = dst.data() + du * lower_dims; |
| 69 | switch (axis) |
| 70 | { |
| 71 | case 0: |
| 72 | { |
| 73 | const int elems = src.shape()[0]; |
| 74 | const T normalization_value = sqrt(std::max(sum[du], static_cast<T>(epsilon))); |
| 75 | std::transform(src_row_ptr, src_row_ptr + elems, dst_row_ptr, |
| 76 | [normalization_value](T val) { return val / normalization_value; }); |
| 77 | } |
| 78 | break; |
| 79 | case 1: |
| 80 | case 2: |
| 81 | { |
| 82 | for (int ld = 0; ld < lower_dims; ++ld) |
| 83 | { |
| 84 | const T normalization_value = |
| 85 | sqrt(std::max(sum[ld % lower_dims_sum + du * lower_dims_sum], static_cast<T>(epsilon))); |
| 86 | dst_row_ptr[ld] = src_row_ptr[ld] / normalization_value; |
| 87 | } |
| 88 | } |
| 89 | break; |
| 90 | default: |
| 91 | ARM_COMPUTE_ERROR("Axis not supported"); |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | return dst; |
| 96 | } |
| 97 | |
| 98 | template SimpleTensor<float> l2_normalize(const SimpleTensor<float> &src, unsigned int axis, float epsilon); |
| 99 | template SimpleTensor<half> l2_normalize(const SimpleTensor<half> &src, unsigned int axis, float epsilon); |
nothing calls this directly
no test coverage detected