// File: kernel.cpp
// Reference-scalar rms_norm fp32.
// LLM target: replace this file with an optimised inner_rms_norm.
// All per-definition constants live in rms_norm_def:: (rms_norm.h).
#include "rms_norm.h"
#include <cmath>

using namespace rms_norm_def;

extern "C" void inner_rms_norm(const float* x, float* output, const float* weight, int M)
{
    for (int m = 0; m < M; ++m) {
        const float* x_row   = x + (long)m * D;
        float*       out_row = output + (long)m * D;

        double sq_sum = 0.0;
        for (int d = 0; d < D; ++d) {
            sq_sum += (double)x_row[d] * (double)x_row[d];
        }
        const float rms = std::sqrt((float)(sq_sum / D) + Eps);

        for (int d = 0; d < D; ++d) {
            out_row[d] = (x_row[d] / rms) * weight[d];
        }
    }
}