Skip to content

fix: Compute MeanStdDevNormalization variance from centred values - #1329

Open
0xzcr wants to merge 1 commit into
ARM-software:mainfrom
0xzcr:fix/meanstddevnorm-variance
Open

0xzcr wants to merge 1 commit into
ARM-software:mainfrom
0xzcr:fix/meanstddevnorm-variance

Conversation

@0xzcr

@0xzcr 0xzcr commented Nov 26, 2026 •

Copy link
Copy Markdown

Problem

NEMeanStdDevNormalizationLayer returns NaN for rows whose mean is large compared with their spread. The NEON kernels compute the variance in one pass:

  • src/cpu/kernels/meanstddevnorm/generic/neon/impl.cpp (fp32): var = (sum_sq / N) - (mean * mean)
  • src/cpu/kernels/meanstddevnorm/generic/neon/fp16.cpp (fp16): the same, with mean rounded to float16_t before mean * mean

The two terms nearly cancel, rounding can make var negative, and 1 / sqrt(var + epsilon) returns NaN for the whole row. In fp16 this starts at small offsets because the rounded mean is off by up to half an fp16 step (0.03 around 100), and its square is then off by more than the real variance. Rows around 10 ± 0.1 or 100 ± 1 already fail. In fp32 it needs |mean| / std of a few thousand, e.g. 300 ± 0.1.

It was found through OpenVINO, which uses this function for LayerNorm / MVN on Arm CPUs. f16 is OpenVINO's default inference precision there: openvinotoolkit/openvino#40324.

Change

  • Kernels: corrected two-pass algorithm. Pass 1 computes the mean m, with the same summation as before. Pass 2 sums d = x − m and d². Then variance = Σd²/N − (Σd/N)², clamped at 0, and output = ((x − m) − Σd/N) · stddev_inv. Subtracting Σd/N removes the rounding error of the mean from both the variance and the output, so constant rows give exact zeros.
  • fp16: the same, with the mean, the sums and the output computed in fp32 and converted to fp16 once when stored. The sums use two accumulator chains, like the existing pass 1.
  • In-place: the first two passes only read, and the output pass reads each element before writing it, so in-place use (input == output) stays correct.
  • Reference: computes in double, with the variance from centred values. It used the same one-pass formula.
  • Tests: a new MeanStdDevNormalizationLayerOffsetValidationFixture fills inputs uniformly in [offset − spread, offset + spread]. The existing fixture is unchanged, so the CL tests that share it are unaffected. New PRECOMMIT FP16/RunLargeMean and FP32/RunLargeMean (72 cases):
    • row widths 3, 7, 9, 17, 33 and 768, so rows shorter than a vector and tails after full 4- and 8-lane vectors;
    • in-place and out-of-place, epsilon 1e-8;
    • large offsets (FP32 1e4 ± 1, FP16 100 ± 1), constant rows (FP32 1000.1, FP16 100.1) and nearly constant rows (FP32 1000.1 ± 1e-3, FP16 100 ± 0.1).

5 files, +191 / −69.

Testing

arm_compute_validation --filter='.*MeanStdDevNormalizationLayer.*', with identical results in both setups:

  • macOS arm64 (Apple M2 Max), Apple clang, arch=arm64-v8.2-a
  • native arm64 Linux, GCC 11.5.0, os=linux arch=arm64-v8.2-a, default Werror=1, no warnings
Kernel precommit (93) nightly (11)
parent 35 passed, 58 failed 11 passed
first revision of this PR 59 passed, 34 failed (all FP32 RunLargeMean) 11 passed
this revision 93 passed (seeds 12345, 1, 777, 31337) 11 passed

A row of three 1000.1f values with epsilon 1e-8f (GCC 11.5) gives 0.000194557622 per element for the parent, 0.520977914 for the first revision of this PR and 0 for this revision.

Through OpenVINO's CPU plugin (macOS), which calls this function for MVN:

Check Before After
261 edge cases vs a float64 reference: widths 1–4096, offsets up to 1e4, constant and all-zero rows, spreads of 1e-4 to 1e15, outliers, alternating ±1000, eps down to 1e-9, fp32 and fp16 49 cases with NaN 0 NaN, no case less accurate
Worst max abs error (outputs ~N(0,1)) NaN fp32 4.2e-6, fp16 1.6e-2 (fp16 output rounding)
OpenVINO MVN / LayerNorm functional tests 1448 passed 1448 passed

clang-format 14.0.6 and scripts/format_code.py --check_formatting --check_copyright pass on all five files.

Cost

Per-node profiling inside real models (all-MiniLM-L6-v2, DeiT-tiny, Whisper-tiny encoder): the kernel takes about 1.75x as long as before (1.6x to 1.9x, fp16 and fp32), because of the extra pass over each row. MVN is 0.4–1.2% of these models' run time, so whole-model time changes by about 1% or less.

Not tested: other target variants. SVE builds use the same NEON files.

@morgolock morgolock left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please address two points before merging:

  1. FP32 regression in impl.cpp:76–99. A row of three 1000.1f values with epsilon=1e-8f should produce zeros. On native Arm/GCC 11.5, the parent returns approximately 0.000194558 per element; this patch returns 0.520978. The new centred variance amplifies the existing rounding error in the mean. Please stabilize the mean accumulation too.

  2. Add ACL regression coverage. Add FP16/FP32 cases for large offsets, constant and nearly constant rows, vector tails and in-place execution in tests/validation/NEON/MeanStdDevNormalizationLayer.cpp, using a stable reference. The current reference still uses E[x²] - mean².

All 29 existing tests pass on both revisions, so they do not catch these cases.

The NEON kernels compute the variance in one pass as E[x^2] - mean^2.
When the mean is large compared with the spread, the two terms nearly
cancel and rounding can make the variance negative, so
1 / sqrt(var + epsilon) returns NaN for the whole row. The fp16 kernel
also rounds the mean to fp16 before squaring it, so it fails at small
offsets already, e.g. rows around 10 +- 0.1 or 100 +- 1.

Use the corrected two-pass algorithm: compute the mean, then sum the
centred values d = x - mean and their squares. The variance is
sum(d^2) / N - (sum(d) / N)^2, and the output also subtracts
sum(d) / N, which removes the rounding error of the mean, e.g. for
constant rows. The fp16 kernel does this in fp32.

Compute the reference in double with the variance from centred
values, and add FP16/FP32 tests for large offsets, constant and nearly
constant rows, vector tails and in-place execution.

Reported in openvinotoolkit/openvino#40324

Signed-off-by: Umang <umangsharma1189@gmail.com>
@0xzcr
0xzcr force-pushed the fix/meanstddevnorm-variance branch from 2e03983 to a2f8caf Compare November 26, 2026 17:13
@0xzcr

0xzcr commented Nov 26, 2026

Copy link
Copy Markdown
Author

Thanks for the review. Both points are addressed in the new revision.

1. FP32 regression with constant rows. Confirmed: three 1000.1f values with epsilon=1e-8f gave 0.5209779 per element here too. The rounding error δ of the mean ended up inside the centred variance, since Σ(x − m)²/N = var + δ², and from there in the output. The kernels now use the corrected two-pass algorithm (Chan, Golub and LeVeque). The second pass also accumulates Σd with d = x − m:

  • variance = Σd²/N − (Σd/N)², clamped at 0
  • output = ((x − m) − Σd/N) · stddev_inv

This corrects the mean by its own rounding error, instead of making the first-pass summation more precise, so it works whatever the summation order. The first-pass sum is unchanged. The case above now returns exact zeros. The FP16 kernel does the same in fp32. It also improves accuracy at large offsets: the worst FP32 error on my edge-case set (offsets up to 1e4) went from 3.4e-3 to 4.2e-6.

2. Regression coverage.

  • Reference: computes in double, with the variance from centred values.
  • Fixture: a new MeanStdDevNormalizationLayerOffsetValidationFixture fills inputs uniformly in [offset − spread, offset + spread]. The existing fixture and its setup() are unchanged, so the CL tests that share it are unaffected.
  • Tests: new PRECOMMIT FP16/RunLargeMean and FP32/RunLargeMean, 72 cases in total:
    • row widths 3, 7, 9, 17, 33 and 768, so rows shorter than a vector and tails after full 4- and 8-lane vectors;
    • in-place and out-of-place, epsilon 1e-8;
    • large offsets (FP32 1e4 ± 1, FP16 100 ± 1), constant rows (FP32 1000.1, FP16 100.1) and nearly constant rows (FP32 1000.1 ± 1e-3, FP16 100 ± 0.1).

Results with arm_compute_validation --filter='.*MeanStdDevNormalizationLayer.*' on macOS arm64 (Apple M2 Max, Apple clang, arch=arm64-v8.2-a):

Kernel precommit (93) nightly (11)
parent 35 passed, 58 failed 11 passed
previous revision of this PR 59 passed, 34 failed (all FP32 RunLargeMean, including the 1000.1f rows) 11 passed
this revision 93 passed (seeds 12345, 1, 777, 31337) 11 passed

The results are identical on native arm64 Linux with GCC 11.5.0 (os=linux, default Werror=1, no warnings). A standalone run of your case there gives 0.000194557622 per element for the parent, 0.520977914 for the previous revision and 0 for this revision.

Cost: in per-node profiling inside real models, the kernel now takes about 1.75x as long as the parent (1.6x to 1.9x, FP16 and FP32), up from about 1.65x in the previous revision.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants