Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion mlx/backend/cuda/layer_norm.cu
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@ struct BlockBroadcastReduce {
block.sync();
x = warp.thread_rank() < warp.meta_group_size() ? temp[warp.thread_rank()]
: init_value;
return cg::reduce(warp, x, op);
x = cg::reduce(warp, x, op);
// All warps must finish reading temp before the next reduction writes it.
block.sync();
return x;
}

__device__ T Sum(const T& input) {
Expand Down
4 changes: 3 additions & 1 deletion mlx/backend/cuda/rms_norm.cu
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ struct BlockBroadcastReduce {
block.sync();
x = warp.thread_rank() < warp.meta_group_size() ? temp[warp.thread_rank()]
: init_value;
return cg::reduce(warp, x, op);
x = cg::reduce(warp, x, op);
block.sync();
return x;
} else {
return x;
}
Expand Down
78 changes: 78 additions & 0 deletions python/tests/test_fast.py
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,50 @@ def inner(x, w, y):
self.assertLess(mx.abs(gx1 - gx2).max(), 1e-5)
self.assertLess(mx.abs(gw1 - gw2).max() / mx.abs(gw1).mean(), 1e-5)

def test_rms_norm_vjp_shared_scratch(self):
for dtype, tolerance in (
(mx.float32, 1e-4),
(mx.float16, 1e-2),
(mx.bfloat16, 8e-2),
):
# Multiple rows per CUDA block exercise reduction scratch reuse.
for rows, width, w_stride in (
(1, 1024, 1),
(2048, 1024, 1),
(2048, 512, 1),
(3, 1025, 1),
(3, 4096, 1),
(3, 1024, 2),
):
with self.subTest(
dtype=dtype, rows=rows, width=width, w_stride=w_stride
):
x = (mx.arange(rows * width).reshape(rows, width) % 31).astype(
dtype
) / 8
w = (mx.arange(width * w_stride) % 5).astype(dtype) / 16 + 0.75
w = w[::w_stride]
g = (mx.arange(rows * width).reshape(rows, width) % 13).astype(
dtype
) / 16
mx.eval(x, w, g)
actual, actual_grads = mx.vjp(
lambda x, w: mx.fast.rms_norm(x, w, 1e-5), [x, w], [g]
)
expected, expected_grads = mx.vjp(
lambda x, w: rms_norm(x, w, 1e-5), [x, w], [g]
)
mx.eval(actual, actual_grads, expected, expected_grads)
for name, result, reference in zip(
("y", "dx", "dw"),
actual + actual_grads,
expected + expected_grads,
):
with self.subTest(output=name):
self.assertEqualArray(
result, reference, atol=tolerance, rtol=tolerance
)

def test_cross_entropy(self):
def cross_entropy_ref(logits, targets):
score = mx.take_along_axis(logits, mx.expand_dims(targets, -1), -1).squeeze(
Expand Down Expand Up @@ -779,6 +823,40 @@ def inner(x, w, b, y):
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?

for dtype, tolerance in (
(mx.float32, 1e-4),
(mx.float16, 1e-2),
(mx.bfloat16, 8e-2),
):
for width in (32, 128, 1024, 4096):
with self.subTest(dtype=dtype, width=width):
x = (mx.arange(3 * width).reshape(3, width) % 31).astype(dtype) / 8
w = (mx.arange(width) % 5).astype(dtype) / 16 + 0.75
b = (mx.arange(width) % 3).astype(dtype) / 8
g = (mx.arange(3 * width).reshape(3, width) % 13).astype(dtype) / 16
mx.eval(x, w, b, g)
actual, actual_grads = mx.vjp(
lambda x, w, b: mx.fast.layer_norm(x, w, b, 1e-5),
[x, w, b],
[g],
)
expected, expected_grads = mx.vjp(
lambda x, w, b: layer_norm(x, w, b, 1e-5),
[x, w, b],
[g],
)
mx.eval(actual, actual_grads, expected, expected_grads)
for name, result, reference in zip(
("y", "dx", "dw", "db"),
actual + actual_grads,
expected + expected_grads,
):
with self.subTest(output=name):
self.assertEqualArray(
result, reference, atol=tolerance, rtol=tolerance
)

def test_layer_norm_grad_no_bias(self):
# Second-order gradient through layer_norm with weight but no bias.
# Regression test: the VJP fallback had zeros_like(w) instead of
Expand Down
30 changes: 30 additions & 0 deletions tests/cuda_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@

#include <cuda_runtime.h>

#include <cmath>
#include <cstdint>
#include <limits>
#include <vector>

using namespace mlx::core;

Expand Down Expand Up @@ -119,3 +121,31 @@ TEST_CASE("test eval after cuda error") {
CHECK_NOTHROW(eval(a));
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.

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

constexpr int width = 1024;
std::vector<float> data(width), expected(width);
double mean_value = 0;
for (int i = 0; i < width; ++i) {
data[i] = 2.0f + (i % 31 - 15) * 0.125f;
mean_value += data[i];
}
mean_value /= width;
double variance = 0;
for (float value : data) {
variance += (value - mean_value) * (value - mean_value);
}
const double inv = 1.0 / std::sqrt(variance / width + 1e-5);
for (int i = 0; i < width; ++i) {
expected[i] = (data[i] - mean_value) * inv;
}
auto x = array(data.data(), {1, width});
auto reference = array(expected.data(), {1, width});
auto w = ones({width});
auto b = zeros({width});
eval(x, reference, w, b);
for (int i = 0; i < 8; ++i) {
auto y = fast::layer_norm(x, w, b, 1e-5f);
CHECK(allclose(y, reference, 3e-5f, 3e-5f).item<bool>());
}
}