Skip to content

Commit db1aff6

Browse files
[Common] Check that grouped GEMM matrix pointers are 16-byte aligned (#3845)
* [PyTorch][Common] Handle grouped GEMM outputs that are not 16-byte aligned cuBLASLt grouped GEMM needs 16-byte aligned matrix pointers. Megatron-LM packs parameters into its gradient buffer without padding when the distributed optimizer is off, so expert main_grad views can start off a 16-byte boundary, and the grouped wgrad GEMM then faults with a misaligned address and aborts the process. - general_grouped_gemm_for_grouped_tensor computes unquantized outputs that are not 16-byte aligned, discrete or grouped, through aligned buffers and copies or adds the result. te.ops.GroupedLinear and te.pytorch.GroupedLinear therefore accept such main_grad views, with discrete or single grouped weights and with delayed wgrad. - The grouped GEMM checks matrix pointer alignment on the host and raises an error that names the operand instead of faulting on the device. Signed-off-by: Siddhant Rajhans <51508945+siddhant-rajhans@users.noreply.github.com> * [PyTorch] Stage a misaligned grouped GEMM output as a copy of the output Run the same GEMM, with the same accumulate, alpha, beta and bias, on an aligned copy of the output and copy the result back. Accumulation and bias then follow the direct path exactly, instead of rounding the product to the output dtype and adding bias before the old output; an explicit beta is supported too. Tests compare misaligned outputs with aligned ones bit for bit, including a grouped output with bias and accumulation. Signed-off-by: Siddhant Rajhans <51508945+siddhant-rajhans@users.noreply.github.com> * [PyTorch] Copy a misaligned output into the staging buffer when beta is given The GEMM reads the output as C when it accumulates or when an explicit beta is passed, so the staging buffer must start as a copy of the output in both cases. Adds a test that compares an explicit beta on a misaligned output with an aligned one bit for bit. Signed-off-by: Siddhant Rajhans <51508945+siddhant-rajhans@users.noreply.github.com> * [PyTorch] Raise on a misaligned grouped GEMM output instead of staging it Remove the aligned staging copy: it adds a hidden device-to-device copy for every misaligned output, and the caller can align its buffers instead (in Megatron-LM, by padding the gradient buffer that main_grad views point into). A misaligned output now stops at the host-side pointer check with a clear error. The tests check that error, that the output is left untouched and that no CUDA error is left behind. Signed-off-by: Siddhant Rajhans <51508945+siddhant-rajhans@users.noreply.github.com> * GroupedMLP test not needed. Already testing feature via grouped tensor ggemm Removed the test for unaligned main gradient handling in grouped GEMM. Signed-off-by: vthumbe1503 <vthumbe@nvidia.com> --------- Signed-off-by: Siddhant Rajhans <51508945+siddhant-rajhans@users.noreply.github.com> Signed-off-by: vthumbe1503 <vthumbe@nvidia.com> Co-authored-by: vthumbe1503 <vthumbe@nvidia.com>
1 parent c2b5a32 commit db1aff6

2 files changed

Lines changed: 93 additions & 0 deletions

File tree

‎tests/pytorch/test_grouped_linear.py‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1286,6 +1286,76 @@ def test_grouped_gemm_grouped_tensor(z, m, n, k, case, layout, accumulate, use_b
12861286
torch.testing.assert_close(o, o_ref, **tols)
12871287

12881288

1289+
@pytest.mark.parametrize("out_kind", ["discrete", "grouped"])
1290+
@pytest.mark.parametrize("out_dtype", [torch.float32, torch.bfloat16])
1291+
@pytest.mark.parametrize("accumulate", [False, True])
1292+
def test_grouped_gemm_grouped_tensor_unaligned_out(out_kind, out_dtype, accumulate) -> None:
1293+
"""An output that is not 16-byte aligned raises an error instead of faulting on the device.
1294+
1295+
A view into a larger buffer need not be aligned, e.g. a Megatron-LM expert main_grad in a
1296+
gradient buffer that packs parameters without padding.
1297+
"""
1298+
if not is_module_grouped_tensor_path_supported(None, torch.bfloat16):
1299+
pytest.skip("Grouped GEMM is not supported on this device or cuBLASLt version.")
1300+
1301+
torch.manual_seed(0)
1302+
dtype = torch.bfloat16
1303+
device = torch.device("cuda")
1304+
n, k = 256, 128
1305+
m_sizes = [64, 32, 96]
1306+
z = len(m_sizes)
1307+
grouped_A = _make_grouped_tensor_from_splits(m_sizes, k, device, dtype) # input
1308+
grouped_B = _make_grouped_tensor_from_splits(m_sizes, n, device, dtype) # grad_output
1309+
_pack_grouped_tensor(
1310+
grouped_A, [torch.randn(ms, k, dtype=dtype, device=device) for ms in m_sizes]
1311+
)
1312+
_pack_grouped_tensor(
1313+
grouped_B, [torch.randn(ms, n, dtype=dtype, device=device) for ms in m_sizes]
1314+
)
1315+
1316+
# wgrads in one buffer, starting one element past a 16-byte boundary
1317+
buffer = torch.randn(1 + z * n * k, dtype=out_dtype, device=device)
1318+
before = buffer.clone()
1319+
if out_kind == "discrete":
1320+
out = list(buffer[1:].view(z, n, k).unbind(0))
1321+
else:
1322+
out = GroupedTensor.make_grouped_tensor_from_rowwise_data(
1323+
num_tensors=z, tensor_shape=(n, k), rowwise_data=buffer[1:], dtype=out_dtype
1324+
)
1325+
1326+
with pytest.raises(RuntimeError, match="data pointer must be 16-byte aligned"):
1327+
general_grouped_gemm_for_grouped_tensor(
1328+
grouped_A, grouped_B, out, layout="NT", accumulate=accumulate
1329+
)
1330+
torch.cuda.synchronize() # no asynchronous CUDA error is left behind
1331+
torch.testing.assert_close(buffer, before, rtol=0, atol=0)
1332+
1333+
1334+
def test_grouped_gemm_grouped_tensor_unaligned_input() -> None:
1335+
"""An input that is not 16-byte aligned raises an error instead of faulting on the device."""
1336+
if not is_module_grouped_tensor_path_supported(None, torch.bfloat16):
1337+
pytest.skip("Grouped GEMM is not supported on this device or cuBLASLt version.")
1338+
1339+
dtype = torch.bfloat16
1340+
device = torch.device("cuda")
1341+
n, k = 256, 128
1342+
m_sizes = [64, 32, 96]
1343+
z = len(m_sizes)
1344+
buffer = torch.randn(1 + z * n * k, dtype=dtype, device=device)
1345+
weights = GroupedTensor.make_grouped_tensor_from_rowwise_data(
1346+
num_tensors=z, tensor_shape=(n, k), rowwise_data=buffer[1:], dtype=dtype
1347+
)
1348+
grouped_x = _make_grouped_tensor_from_splits(m_sizes, k, device, dtype)
1349+
_pack_grouped_tensor(
1350+
grouped_x, [torch.randn(ms, k, dtype=dtype, device=device) for ms in m_sizes]
1351+
)
1352+
grouped_y = _make_grouped_tensor_from_splits(m_sizes, n, device, dtype)
1353+
1354+
with pytest.raises(RuntimeError, match="A data pointer must be 16-byte aligned"):
1355+
general_grouped_gemm_for_grouped_tensor(weights, grouped_x, grouped_y, layout="TN")
1356+
torch.cuda.synchronize() # no asynchronous CUDA error is left behind
1357+
1358+
12891359
@pytest.mark.parametrize("use_bias_scale", [False, True])
12901360
def test_grouped_gemm_grouped_tensor_zero_work_bias(use_bias_scale) -> None:
12911361
"""A grouped bias operation is a no-op when every group has zero rows.

‎transformer_engine/common/gemm/cublaslt_grouped_gemm.cu‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -573,6 +573,19 @@ inline OperandStorageChoice choose_grouped_operand_storage(bool trans, bool is_A
573573
return {true, false, trans};
574574
}
575575

576+
// cuBLASLt grouped GEMM requires 16-byte aligned matrix pointers, but a view into a larger
577+
// buffer need not be (e.g. a wgrad output in an unpadded gradient buffer). Check on the host:
578+
// a misaligned pointer otherwise fails inside the kernel with a misaligned address error.
579+
template <typename... Args>
580+
inline void check_grouped_gemm_ptr_alignment(const transformer_engine::SimpleTensor &data,
581+
const Args &...operand) {
582+
if (data.numel() == 0) return;
583+
const auto misalignment = reinterpret_cast<uintptr_t>(data.dptr) % 16;
584+
NVTE_CHECK(misalignment == 0, "Grouped GEMM: ", operand...,
585+
" data pointer must be 16-byte aligned, but it is ", misalignment,
586+
" bytes past a 16-byte boundary.");
587+
}
588+
576589
// Build Kernel Arguments detailing out addresses and other metadata for list of C/D tensors
577590
// passed to the grouped GEMM kernel. Use-case: C/D --> List of wgrads for experts in MOE
578591
inline MultiTensorGroupGemmOutputArgs build_grouped_gemm_multi_out_args(
@@ -600,6 +613,7 @@ inline MultiTensorGroupGemmOutputArgs build_grouped_gemm_multi_out_args(
600613
transformer_engine::to_string(t->dtype()));
601614
const auto &shape = t->shape();
602615
NVTE_CHECK(shape.size() == 2, "Grouped GEMM: ", name, "_list tensor ", i, " must be 2D.");
616+
check_grouped_gemm_ptr_alignment(t->data, name, "_list tensor ", i);
603617
args.data_ptrs[i] = t->data.dptr;
604618
args.rows[i] = static_cast<int>(shape[1]);
605619
args.cols[i] = static_cast<int>(shape[0]);
@@ -627,6 +641,7 @@ inline MultiTensorGroupGemmInputArgs build_grouped_gemm_multi_inputA_args(
627641
use_rowwise ? t->scale_inv : t->columnwise_scale_inv;
628642
NVTE_CHECK(data.has_data(), "Grouped GEMM: ", name, "_list tensor ", i,
629643
" is missing required data.");
644+
check_grouped_gemm_ptr_alignment(data, name, "_list tensor ", i);
630645
args.data_ptrs[i] = data.dptr;
631646
const auto &shape = t->shape();
632647
NVTE_CHECK(shape.size() == 2, "Grouped GEMM: ", name, "_list tensor ", i, " must be 2D.");
@@ -819,6 +834,10 @@ inline GroupedOperandSelection select_grouped_operand(const transformer_engine::
819834
} else {
820835
use_columnwise(choice.storage_transposed);
821836
}
837+
// With 16-byte rows (checked in launch_grouped_gemm_setup), every group is aligned when the
838+
// base pointer is.
839+
check_grouped_gemm_ptr_alignment(choice.use_rowwise ? t->data : t->columnwise_data,
840+
is_A ? "A" : "B");
822841
return sel;
823842
}
824843

@@ -1624,6 +1643,10 @@ inline void launch_grouped_gemm_setup(
16241643
check_uniform_last_dim_alignment(B_meta, B_sel.dtype, "B");
16251644
if (!d_is_discrete) {
16261645
check_uniform_last_dim_alignment(D_meta, d_dtype, "D");
1646+
check_grouped_gemm_ptr_alignment(D->data, "D");
1647+
}
1648+
if (!c_is_discrete) {
1649+
check_grouped_gemm_ptr_alignment(C->data, "C");
16271650
}
16281651

16291652
const int threads_per_block = 256;

0 commit comments

Comments
 (0)