Skip to content

[CUDA] Synchronize LayerNorm reduction scratch reuse - #4866

Merged
nastya236 merged 7 commits into
ml-explore:mainfrom
strayberry:fix/cuda-layernorm-scratch-reuse
Nov 24, 2026
Merged

nastya236 merged 7 commits into
ml-explore:mainfrom
strayberry:fix/cuda-layernorm-scratch-reuse

Conversation

@strayberry

@strayberry strayberry commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor
  • I understand it is strictly prohibited to use AI to write PR description
  • AI usage disclosure: Codex assisted with the implementation, regression tests, experiments, and PR description. I reviewed the changes and validation results and take responsibility for this contribution.

Consecutive BlockBroadcastReduce::Sum calls in CUDA LayerNorm can overwrite shared scratch before every warp finishes reading it. The existing barrier orders writes before reads, but does not protect scratch reuse.

Add a block barrier after the final warp reduction, before the helper returns. The helper is shared by the forward and VJP kernels.

Validation

Linux / GB10

Baseline: fc344c986. NVIDIA GB10 (sm_121), Linux aarch64, GCC 13.3, CUDA 13.0.88, cuDNN 9.13.0; fresh C++ CUDA build with CPU and Python bindings disabled.

Check under Compute Sanitizer racecheck Before After
1×1024 float32 LayerNorm Read/write hazard; 1024 incorrect outputs, max absolute error 0.535446 No hazards; max absolute error below 2.4e-7
New shared-scratch regression 8/8 assertions fail 8/8 assertions pass

The one-row API failure and fix also reproduce with MLX_USE_CUDA_GRAPHS=0. Ordinary serial runs pass on both versions and do not expose this race.

  • New tests: host-reference scratch check and forward/VJP comparisons for float32, float16 and bfloat16 at widths 32/128/1024/4096. Together: 56 assertions pass under racecheck, 0 hazards.
  • All cuda_tests.cpp cases: 4 cases, 67 assertions pass.
  • Standalone forward/VJP matrix: 60/60 patched configurations pass (both CUDA Graphs settings, three dtypes, widths through 8192, rows 1/3, four iterations each).
  • Full pre-commit checks pass with PYTHONUTF8=1 on Windows. The full Python suite and Metal validation were not run.

To reproduce the baseline failure, apply only the tests/cuda_tests.cpp changes to fc344c986. Build each version with CUDA and MLX_BUILD_TESTS=ON, then run:

compute-sanitizer --tool racecheck --racecheck-report analysis --error-exitcode 86 \
  build/tests/tests --test-case="test CUDA layer norm shared scratch"

Windows / RTX 4060 Ti

Windows x64, RTX 4060 Ti (sm_89, WDDM), driver 610.88, MSVC 19.44, CUDA 13.0.48, cuDNN 9.19, Compute Sanitizer 2025.3. The exact PR commit 7d0af56dd was built incrementally as a CPU+CUDA shared library. The same test executable was run against separate baseline and patched DLLs.

Check Baseline Unmodified PR
Shared-scratch regression under racecheck, CUDA Graphs on/off 8/8 assertions fail; 8 reported hazards All 8 assertions pass; 0 hazards
Both new tests under racecheck, CUDA Graphs on/off — 56/56 assertions pass; 0 hazards
All cuda_tests.cpp cases — 6 cases, 72/72 assertions pass

These runs also encounter the separate DLL-teardown issue tracked by #4867: ordinary baseline and patched runs exit 2170, as do patched racecheck runs. Baseline racecheck exits 86 for detected hazards.

With the same WDDM lifetime fix from #4867 applied to both DLLs, ordinary tests exit 0. The patched CUDA suite passes 72/72 assertions, the existing LayerNorm bias-gradient regression passes, and the standalone forward/VJP matrix passes 60/60 configurations with no incorrect values. Two initially empty output logs were rechecked with synchronous capture.

Initial racecheck runs with this additional WDDM fix timed out during process termination using Compute Sanitizer 2025.3. A tool-version control using 2025.4.0.0 (build 36782660) from the installed CUDA 13.1 package completes with the same test executable, MLX DLLs, CUDA 13.0 build/runtime environment and driver. With CUDA Graphs on/off, the baseline scratch test fails 8/8 assertions, reports 8 hazards and exits 86; both patched tests pass 56/56 assertions, 0 hazards and exit 0, twice per Graphs setting (four runs). This isolates the observed hang to the older sanitizer configuration, consistent with NVIDIA's documented Windows exit-hang fixes.

Windows timings remain excluded from the performance comparison because processes left by the 2025.3 runs continued consuming CPU during those measurements.

Windows regression command after a Visual Studio CUDA build:

compute-sanitizer --tool racecheck --racecheck-report analysis --error-exitcode 86 .\build\Release\tests.exe '--test-case=test CUDA layer norm shared scratch'

Performance

GB10 results: float32, width 1024; median (range) in µs/op, including host submission and GPU completion. The ranges overlap, and small-input timings vary substantially.

Rows Baseline Patched
4096 161.15 (159.03–164.14) 159.37 (157.86–161.27)
1 11.30 (10.20–13.16) 10.77 (9.71–11.64)
Timing program and build instructions

Runs alternate baseline/patched/patched/baseline (A–B–B–A). Each invocation uses ten warmups and five rounds of 1000 operations. Discarding the first round leaves eight measured rounds per version.

Save the following as layernorm_bench.cpp and build it separately against each MLX installation:

cmake_minimum_required(VERSION 3.25)
project(layernorm_bench LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
find_package(MLX CONFIG REQUIRED)
find_package(CUDAToolkit REQUIRED)
add_executable(layernorm_bench layernorm_bench.cpp)
target_link_libraries(layernorm_bench PRIVATE mlx CUDA::cudart)
cmake -S . -B bench -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="$MLX_INSTALL"
cmake --build bench -j2
./bench/layernorm_bench 4096
./bench/layernorm_bench 1
#include "mlx/mlx.h"

#include <chrono>
#include <iostream>
#include <vector>

namespace mx = mlx::core;

void benchmark(int rows) {
  constexpr int width = 1024;
  constexpr int repeats = 1000;
  mx::set_default_device(mx::Device::gpu);
  mx::set_cache_limit(128ULL << 20);
  std::vector<float> data(rows * width), weights(width), biases(width);
  for (int j = 0; j < width; ++j) {
    weights[j] = 0.75f + (j % 5) * 0.0625f;
    biases[j] = (j % 3 - 1) * 0.125f;
    for (int r = 0; r < rows; ++r) {
      data[r * width + j] = 2.0f + ((j + r) % 31 - 15) * 0.125f;
    }
  }
  auto x = mx::array(data.data(), {rows, width});
  auto w = mx::array(weights.data(), {width});
  auto b = mx::array(biases.data(), {width});
  mx::eval(x, w, b);
  for (int i = 0; i < 10; ++i) {
    mx::eval(mx::fast::layer_norm(x, w, b, 1e-5f));
  }
  for (int round = 0; round < 5; ++round) {
    const auto start = std::chrono::steady_clock::now();
    for (int i = 0; i < repeats; ++i) {
      mx::async_eval(mx::fast::layer_norm(x, w, b, 1e-5f));
    }
    mx::synchronize();
    const double us = std::chrono::duration<double, std::micro>(
                          std::chrono::steady_clock::now() - start)
                          .count();
    std::cout << "rows=" << rows << " round=" << round
              << " us_per_op=" << us / repeats << '\n';
  }
}

int main(int argc, char** argv) {
  benchmark(argc > 1 ? std::stoi(argv[1]) : 4096);
  mx::clear_streams();
}

@nastya236

nastya236 commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Thank you for the contribution, that's great. I added a small comment: I think would be better to have vjp test in python rather than in cpp.
Also related to this bug, I checked and we have the same issue with rms_norm_vjp_small . I pushed the fix to your branch.

@nastya236
nastya236 self-requested a review November 17, 2026 01:59
@nastya236 nastya236 added the await response This pull request is waiting for response from the author. label Nov 17, 2026
Move the LayerNorm forward/VJP tests to Python and retain the
C++ shared-scratch regression.

Add RMSNorm VJP coverage for persistent scratch reuse, different
widths, and strided weights. Check outputs and gradients independently
so a failed forward assertion does not skip gradient validation.
@strayberry

Copy link
Copy Markdown
Contributor Author

Thank you for the contribution, that's great. I added a small comment: I think would be better to have vjp test in python rather than in cpp. Also related to this bug, I checked and we have the same issue with rms_norm_vjp_small . I pushed the fix to your branch.

Thank you for the review and for adding the RMSNorm fix! I’ve moved the VJP tests to Python and added RMSNorm regression coverage in 1303f5e. All 11 focused tests pass on Windows and Linux.

@nastya236 nastya236 added await verification This pull request is non-trivial and requires a human expert to verify its correctness. and removed await response This pull request is waiting for response from the author. labels Nov 23, 2026
Comment thread tests/cuda_tests.cpp Outdated
CHECK(array_equal(a, ones({4})).item<bool>());
}

TEST_CASE("test CUDA layer norm shared scratch") {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

A better place for these type of test will be python API.

Comment thread tests/cuda_tests.cpp Outdated
CHECK(array_equal(a, ones({4})).item<bool>());
}

TEST_CASE("test CUDA layer norm shared scratch") {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think this can be removed

Comment thread python/tests/test_fast.py Outdated
self.assertLess(mx.abs(gb1).max(), 1e-9)
self.assertLess(mx.abs(gb2).max(), 1e-9)

def test_layer_norm_vjp_shared_scratch(self):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Maybe we can rename the tests to just test_layer_norm_vjp / test_rms_norm_vjp and generalise it to all the cases?

@nastya236
nastya236 merged commit d20ac3b into ml-explore:main Nov 24, 2026
24 checks passed
rcfa pushed a commit to cubiculum-ai/mlx that referenced this pull request Nov 26, 2026
Co-authored-by: Anastasiia Filippova <[email protected]>

Ported: python/tests/test_fast.py had the fork's older test_rms_norm_grad
and test_layer_norm_grad, which conflicted with Apple's rewrite. Both are
taken as Apple's: they now equal Apple's at this commit.

(cherry picked from commit d20ac3b)
@zcbenz zcbenz removed the await verification This pull request is non-trivial and requires a human expert to verify its correctness. label Nov 28, 2026
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.

3 participants