Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
46 changes: 46 additions & 0 deletions aiter/ops/opus/latent_moe_grouped_gemm_bwd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# SPDX-License-Identifier: MIT
# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved.

"""Draft gfx950 OPUS interface for the Kimi routed-expert linear backward."""

import torch


def latent_moe_grouped_gemm_bwd(
x: torch.Tensor,
weight: torch.Tensor,
dy: torch.Tensor,
expert_offsets: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Differentiate one grouped linear projection, Y_e = X_e @ W_e.T.

Rows are already grouped by local expert. For R routed assignments and E
local experts, x is [R, K], weight is [E, N, K] and dy is [R, N], all
contiguous BF16. The caller supplies contiguous int32 offsets [E+1] on
the same device, nondecreasing from 0 to R. Equal offsets mean an empty
expert. Offset values are a caller precondition to avoid a host sync.

The proposed outputs are dx [R, K] in BF16 (in the same routed order)
and dw [E, N, K] in FP32, zero for empty experts. For Kimi gate/up use
(K, N) = (3584, 3072); for down use (3072, 3584). The caller combines
the two input gradients for gate/up and undoes the routing permutation.

This draft reserves the entry point; the OPUS kernel is pending.
"""
if x.ndim != 2 or dy.ndim != 2 or weight.ndim != 3:
raise ValueError("expected x [R,K], weight [E,N,K], dy [R,N]")
experts, n, k = weight.shape
if x.shape[1] != k or dy.shape != (x.shape[0], n):
raise ValueError("x, weight and dy must agree on R, K and N")
if expert_offsets.shape != (experts + 1,):
raise ValueError("expert_offsets must have E+1 entries")
if not (x.dtype == weight.dtype == dy.dtype == torch.bfloat16):
raise TypeError("x, weight and dy must be BF16")
if expert_offsets.dtype != torch.int32:
raise TypeError("expert_offsets must be int32")
for tensor in (weight, dy, expert_offsets):
if tensor.device != x.device:
raise ValueError("all inputs must share a device")
if not all(t.is_contiguous() for t in (x, weight, dy, expert_offsets)):
raise ValueError("all inputs must be contiguous")
raise NotImplementedError("gfx950 OPUS latent MoE grouped GEMM backward is pending")
76 changes: 76 additions & 0 deletions op_tests/test_latent_moe_grouped_gemm_bwd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# SPDX-License-Identifier: MIT
# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved.

import pytest
import torch


def _inputs(counts, k, n, device="cpu"):
gen = torch.Generator(device=device).manual_seed(35)

def rand(*shape):
return torch.randn(*shape, device=device, generator=gen).to(torch.bfloat16)

rows = sum(counts)
offsets = torch.tensor([0, *counts], device=device).cumsum(0, dtype=torch.int32)
return rand(rows, k), rand(len(counts), n, k), rand(rows, n), offsets


def _reference(x, weight, dy, offsets):
"""FP32 dgrad and wgrad, one independent GEMM per expert."""
dx = torch.empty_like(x, dtype=torch.float32)
dw = torch.zeros_like(weight, dtype=torch.float32)
bounds = offsets.tolist()
for e, (start, end) in enumerate(zip(bounds, bounds[1:])):

Check warning on line 24 in op_tests/test_latent_moe_grouped_gemm_bwd.py

View workflow job for this annotation

GitHub Actions / Check Code Style with Ruff

[ruff] reported by reviewdog 🐶 Prefer `itertools.pairwise()` over `zip()` when iterating over successive pairs Raw Output: message:"Prefer `itertools.pairwise()` over `zip()` when iterating over successive pairs" location:{path:"/home/runner/work/aiter/aiter/op_tests/test_latent_moe_grouped_gemm_bwd.py" range:{start:{line:24 column:38} end:{line:24 column:41}}} severity:WARNING source:{name:"ruff" url:"https://docs.astral.sh/ruff"} code:{value:"RUF007" url:"https://docs.astral.sh/ruff/rules/zip-instead-of-pairwise"} suggestions:{range:{start:{line:6 column:1} end:{line:6 column:1}} text:"import itertools\n"} suggestions:{range:{start:{line:24 column:38} end:{line:24 column:61}} text:"itertools.pairwise(bounds)"}
if start != end:
grad = dy[start:end].float()
dx[start:end] = grad @ weight[e].float()
dw[e] = grad.T @ x[start:end].float()
return dx, dw


@pytest.mark.parametrize("counts", [(0, 1, 5, 0, 2), (0, 0)])
@pytest.mark.parametrize("k,n", [(7, 3), (3, 7)])
def test_reference_against_autograd(counts, k, n):
x, weight, dy, offsets = _inputs(counts, k, n)
dx, dw = _reference(x, weight, dy, offsets)
# An independent forward picks a weight per assignment, including repeats.
ids = torch.arange(len(counts)).repeat_interleave(torch.tensor(counts))
xf = x.float().requires_grad_()
wf = weight.float().requires_grad_()
y = torch.bmm(wf[ids], xf.unsqueeze(-1)).squeeze(-1)
ref_dx, ref_dw = torch.autograd.grad(y, (xf, wf), dy.float())
torch.testing.assert_close(dx, ref_dx)
torch.testing.assert_close(dw, ref_dw)


def test_input_contract():
from aiter.ops.opus.latent_moe_grouped_gemm_bwd import latent_moe_grouped_gemm_bwd

x, w, dy, offsets = _inputs((2, 0, 1), 7, 3)
with pytest.raises(TypeError, match="int32"):
latent_moe_grouped_gemm_bwd(x, w, dy, offsets.long())
with pytest.raises(ValueError, match="E[+]1"):
latent_moe_grouped_gemm_bwd(x, w, dy, offsets[:-1])
with pytest.raises(ValueError, match="agree"):
latent_moe_grouped_gemm_bwd(x, w, dy[:-1], offsets)


@pytest.mark.parametrize("k,n", [(3584, 3072), (3072, 3584)])
def test_gfx950_projection(k, n):
if not torch.version.hip or not torch.cuda.is_available():
pytest.skip("requires gfx950")
if torch.cuda.get_device_properties(0).gcnArchName.split(":")[0] != "gfx950":
pytest.skip("requires gfx950")
from aiter.ops.opus.latent_moe_grouped_gemm_bwd import latent_moe_grouped_gemm_bwd

args = _inputs((1, 0, 17), k, n, device="cuda:0")
try:
dx, dw = latent_moe_grouped_gemm_bwd(*args)
except NotImplementedError as exc:
if str(exc) != "gfx950 OPUS latent MoE grouped GEMM backward is pending":
raise
pytest.skip(str(exc))
ref_dx, ref_dw = _reference(*args)
torch.testing.assert_close(dx, ref_dx.bfloat16(), atol=0.03125, rtol=0.015625)
torch.testing.assert_close(dw, ref_dw, atol=1e-4, rtol=1e-4)
Loading