diff --git a/.github/workflows/pytorchsim_test.yml b/.github/workflows/pytorchsim_test.yml index 147fb7861..4d0a2bf2c 100644 --- a/.github/workflows/pytorchsim_test.yml +++ b/.github/workflows/pytorchsim_test.yml @@ -61,6 +61,7 @@ jobs: - tests/ops/fusion/test_matmul_scalar.py - tests/ops/fusion/test_matmul_vector.py - tests/ops/fusion/test_prologue_fusion.py + - tests/ops/gemm/test_grouped_mm.py - tests/ops/gemm/test_row_matmul.py - tests/ops/misc/test_complex_to_real.py - tests/ops/misc/test_eager_to_compile_recursion.py diff --git a/pytorchsim/frontend/grouped_mm.py b/pytorchsim/frontend/grouped_mm.py new file mode 100644 index 000000000..33f7328d8 --- /dev/null +++ b/pytorchsim/frontend/grouped_mm.py @@ -0,0 +1,124 @@ +"""aten._grouped_mm on the npu (2-D A grouped by offs, times 3-D B) as one Triton kernel in fused_moe form: a +program is a block of BM rows of one group, its group, first row and row count read from a table the TOG takes +as launch data; a block without rows runs its K loop zero times. Registered through torch.library.""" + +import torch +import triton +import triton.language as tl +from torch.library import triton_op, wrap_triton + +from pytorchsim import config + +logger = config.setup_logger() + + +def _tiles(n, k, esize): + """(BM, BN, BK): BM the lanes, BN and BK the largest tile the machine's mm rule gives a BM-row block.""" + from pytorchsim.codegen import tiling + bm = int(config.CONFIG_MACHINE.vector_lanes) + acc = 4 + _, tn, tk = tiling.gemm_tile_candidates(bm, n, k, acc + esize, esize)[0] + return bm, tn, tk + + +@triton.jit +def _grouped_mm_kernel(a_ptr, b_ptr, grp_ptr, start_ptr, rows_ptr, c_ptr, + sbg: tl.constexpr, sbk: tl.constexpr, sbn: tl.constexpr, K: tl.constexpr, KP: tl.constexpr, + N: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr): + pid_m = tl.program_id(0) + pid_n = tl.program_id(1) + g = tl.load(grp_ptr + pid_m) + nr = tl.load(rows_ptr + pid_m) + rm = tl.arange(0, BM) + rows = tl.load(start_ptr + pid_m) + rm + live = rm < nr + rn = pid_n * BN + tl.arange(0, BN) + ncols = rn < N + rk = tl.arange(0, BK) + acc = tl.zeros((BM, BN), dtype=tl.float32) + for k0 in range(0, tl.where(nr > 0, KP, 0), BK): + kk = k0 + rk + a = tl.load(a_ptr + rows[:, None] * K + kk[None, :], mask=live[:, None] & (kk < K)[None, :], other=0.0) + b = tl.load(b_ptr + g * sbg + kk[:, None] * sbk + rn[None, :] * sbn, + mask=(kk < K)[:, None] & ncols[None, :], other=0.0) + acc += tl.dot(a, b) + tl.store(c_ptr + rows[:, None] * N + rn[None, :], acc.to(c_ptr.dtype.element_ty), + mask=live[:, None] & ncols[None, :]) + + +def _blocks(offs, s, g, bm): + """Per block of at most `bm` rows of one group: its group, first row and row count (0 past the last group's + rows); the block count is the most any offs over `s` rows and `g` groups needs, and no more than `s`.""" + end = offs.to(torch.int64) + start = torch.cat([end.new_zeros(1), end[:-1]]) + size = end - start + bend = torch.cumsum((size + bm - 1) // bm, 0) + bstart = torch.cat([bend.new_zeros(1), bend[:-1]]) + nb = min(s, (s + g * (bm - 1)) // bm) + b = torch.arange(nb, device=offs.device) + grp = (b[:, None] >= bend[None, :]).sum(1).clamp(max=g - 1) + j = b - bstart.index_select(0, grp) + first = start.index_select(0, grp) + j * bm + rows = (size.index_select(0, grp) - j * bm).clamp(min=0, max=bm) + return grp.to(torch.int32), first.to(torch.int32), rows.to(torch.int32), nb + + +@triton_op("torchsim::grouped_mm", mutates_args=()) +def grouped_mm(a: torch.Tensor, b: torch.Tensor, offs: torch.Tensor) -> torch.Tensor: + s, k = a.shape + g, _, n = b.shape + bm, bn, bk = _tiles(n, k, a.element_size()) + grp, first, rows, nb = _blocks(offs, s, g, bm) + c = a.new_empty(s, n) + wrap_triton(_grouped_mm_kernel)[(nb, triton.cdiv(n, bn), 1)]( + a.contiguous(), b, grp, first, rows, c, b.stride(0), b.stride(1), b.stride(2), + k, triton.cdiv(k, bk) * bk, n, bm, bn, bk) + return c + + +def _math(a, b, offs, bias, out_dtype): + """Group by group with matmul: rows offs[g-1]:offs[g] of A times B[g] (aten's semantics for 2-D x 3-D).""" + out, lo = [], 0 + for gi, hi in enumerate(offs.tolist()): + out.append(a[lo:hi] @ b[gi]) + lo = hi + c = torch.cat(out) if out else a.new_empty(0, b.shape[-1]) + if bias is not None: + c = c + bias + return c.to(out_dtype) if out_dtype is not None else c + + +def _decline(a, b, offs, bias, out_dtype): + """Why the kernel does not take this call, or None.""" + if a.dim() != 2 or b.dim() != 3 or offs is None: + return f"A {a.dim()}-D, B {b.dim()}-D, offs {'given' if offs is not None else 'none'} (it takes 2-D x 3-D)" + if bias is not None or (out_dtype is not None and out_dtype != a.dtype): + return "a bias or another out_dtype" + if a.dtype != b.dtype: + return f"A {a.dtype} and B {b.dtype}" + if torch.is_grad_enabled() and (a.requires_grad or b.requires_grad): + return "a gradient (the kernel has no backward)" + return None + + +def _aten_grouped_mm(a, b, offs=None, bias=None, out_dtype=None): + why = _decline(a, b, offs, bias, out_dtype) + if why is not None: + logger.info("[grouped_mm] %s x %s: math, %s", tuple(a.shape), tuple(b.shape), why) + return _math(a, b, offs, bias, out_dtype) + if not torch.compiler.is_compiling(): + return _math(a, b, offs, bias, out_dtype) + return grouped_mm(a, b, offs) + + +_lib = None + + +def install(): + """Register aten._grouped_mm's npu kernel above autograd and functionalization, and at the backend key, + where a call made under inference_mode lands.""" + global _lib + if _lib is None: + _lib = torch.library.Library("aten", "IMPL") + for key in ("AutogradPrivateUse1", "PrivateUse1"): + _lib.impl("_grouped_mm", _aten_grouped_mm, key) diff --git a/pytorchsim/frontend/inductor_patches.py b/pytorchsim/frontend/inductor_patches.py index f79869ed9..0837d39a3 100644 --- a/pytorchsim/frontend/inductor_patches.py +++ b/pytorchsim/frontend/inductor_patches.py @@ -656,8 +656,9 @@ def install(): _install_npu_choices() _decompose_convolution_for_npu() _install_selection() - from pytorchsim.frontend import attention + from pytorchsim.frontend import attention, grouped_mm attention.install() + grouped_mm.install() inductor_config.max_autotune_gemm = True inductor_config.max_autotune_gemm_backends = "ATEN,TRITON" diff --git a/pytorchsim/simulator/timing.py b/pytorchsim/simulator/timing.py index d9010e458..c75fd8200 100644 --- a/pytorchsim/simulator/timing.py +++ b/pytorchsim/simulator/timing.py @@ -87,7 +87,7 @@ def write_shape(workdir, meta, args=()): numels = dict(meta["numels"]) if meta.get("template_grid") is not None: grid = list(contract.launch_extents(meta)) - _write_extents(workdir, grid, "template grid") + _write_extents(workdir, grid, "template grid", data_values(workdir, args)) return grid passed = [k for k in numels if not k.startswith("r")] @@ -103,11 +103,28 @@ def write_shape(workdir, meta, args=()): numels[key] = val grid = list(contract.grid_of({**meta, "numels": numels})) - _write_extents(workdir, grid, "grid") + _write_extents(workdir, grid, "grid", data_values(workdir, args)) return grid -def _write_extents(workdir, ext, what): +def data_values(workdir, args): + """The elements of every argument the TOG reads as data (tile_types' data_args), off this launch's arguments; + shape_args carries them past the grid's extents.""" + import json + path = contract.artifact(workdir, "tile_types") + want = json.load(open(path)).get("data_args", []) if path else [] + out = [] + for d in want: + t = args[d["arg"]] + vals = t.detach().reshape(-1).cpu().tolist() + if len(vals) != d["numel"]: + raise ValueError(f"argument {d['arg']} of {workdir} holds {len(vals)} elements, the TOG reads " + f"{d['numel']}") + out += [int(v) for v in vals] + return out + + +def _write_extents(workdir, ext, what, data=()): """Write `ext` as this launch's shape_args, refusing a count it cannot use. The count is checked against the shared TOG; the file goes in this @@ -124,7 +141,7 @@ def _write_extents(workdir, ext, what): f"would read past the end of shape_args. Delete the workdir to " f"rebuild it.") with open(os.path.join(contract.dir_for(workdir), SHAPE_TXT), "w") as f: - f.write("\n".join(str(int(g)) for g in ext) + "\n") + f.write("\n".join(str(int(g)) for g in list(ext) + list(data)) + "\n") logger.info("[TOGSim] %s %s -> %s", what, ext, SHAPE_TXT) diff --git a/scripts/ci/triton_route_passing.txt b/scripts/ci/triton_route_passing.txt index 9655088a2..927f04fff 100644 --- a/scripts/ci/triton_route_passing.txt +++ b/scripts/ci/triton_route_passing.txt @@ -261,6 +261,7 @@ tests/ops/fusion/test_addmm_residual.py tests/ops/fusion/test_matmul_scalar.py tests/ops/fusion/test_matmul_vector.py tests/ops/fusion/test_prologue_fusion.py +tests/ops/gemm/test_grouped_mm.py tests/ops/gemm/test_row_matmul.py tests/ops/misc/test_complex_to_real.py tests/ops/misc/test_eager_to_compile_recursion.py diff --git a/tests/ops/gemm/test_grouped_mm.py b/tests/ops/gemm/test_grouped_mm.py new file mode 100644 index 000000000..b3339ed65 --- /dev/null +++ b/tests/ops/gemm/test_grouped_mm.py @@ -0,0 +1,95 @@ +"""aten._grouped_mm on the npu through the Triton route: rows of A grouped by offs, group g's rows times B[g], +against a float32 CPU reference, group by group. + + routed uneven groups (empty ones, one past BM rows) run as the grouped kernel, no call left to aten + few_rows fewer rows than groups: every block holds rows, the grid stops at the row count + eager outside torch.compile the call runs group by group (no Triton launch outside a compiled graph) + grad inputs that require grad run group by group, and their gradients match the CPU's + +Usage: test_grouped_mm.py [case ...] (all cases when none is named) +""" +import sys + +import torch + +device = torch.device("npu:0") +TOL = 2e-2 + + +def _inputs(sizes, k, n, seed=0): + g = torch.Generator().manual_seed(seed) + a = (torch.randn(sum(sizes), k, generator=g) * 0.1).to(torch.bfloat16) + b = (torch.randn(len(sizes), k, n, generator=g) * 0.1).to(torch.bfloat16) + offs = torch.cumsum(torch.tensor(sizes, dtype=torch.int32), 0, dtype=torch.int32) + return a, b, offs + + +def _reference(a, b, offs): + out, lo = [], 0 + for g, hi in enumerate(offs.tolist()): + out.append(a[lo:hi].float() @ b[g].float()) + lo = hi + return torch.cat(out) + + +def _gmm(a, b, offs): + return torch.nn.functional.grouped_mm(a, b, offs=offs) + + +def _err(out, ref): + return ((out.float().cpu() - ref).abs().max() / ref.abs().max()).item() + + +def _run_compiled(sizes, k, n): + """(relative error, grouped-kernel launches, calls left to aten) of one compiled call.""" + from pytorchsim.driver import codecache + from pytorchsim.frontend import grouped_mm + launches, externs = [], [] + codecache.observe_launches(grouped_mm._grouped_mm_kernel, lambda: launches.append(1)) + codecache.observe_every_extern(externs.append) + a, b, offs = _inputs(sizes, k, n) + torch._dynamo.reset() + out = torch.compile(_gmm, dynamic=False)(a.to(device), b.to(device), offs.to(device)) + return _err(out, _reference(a, b, offs)), len(launches), externs + + +def case_routed(): + err, launched, externs = _run_compiled([0, 130, 7, 0, 64, 1, 0, 30], 256, 256) + return err < TOL and launched == 1 and not externs, f"err {err:.3g}, launches {launched}, externs {externs}" + + +def case_few_rows(): + err, launched, externs = _run_compiled([1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], 256, 256) + return err < TOL and launched == 1 and not externs, f"err {err:.3g}, launches {launched}, externs {externs}" + + +def case_eager(): + a, b, offs = _inputs([3, 0, 9, 4], 128, 128) + out = _gmm(a.to(device), b.to(device), offs.to(device)) + err = _err(out, _reference(a, b, offs)) + return err < TOL, f"err {err:.3g}" + + +def case_grad(): + a, b, offs = _inputs([3, 0, 9, 4], 128, 128) + a_ref, b_ref = a.float().requires_grad_(), b.float().requires_grad_() + _reference(a_ref, b_ref, offs).sum().backward() + a_npu, b_npu = a.to(device).requires_grad_(), b.to(device).requires_grad_() + torch.compile(_gmm, dynamic=False)(a_npu, b_npu, offs.to(device)).float().sum().backward() + ea, eb = _err(a_npu.grad, a_ref.grad), _err(b_npu.grad, b_ref.grad) + return ea < TOL and eb < TOL, f"grad err a {ea:.3g}, b {eb:.3g}" + + +CASES = {"routed": case_routed, "few_rows": case_few_rows, "eager": case_eager, "grad": case_grad} + + +if __name__ == "__main__": + names = sys.argv[1:] or list(CASES) + failed = [] + for name in names: + ok, why = CASES[name]() + print(f"{'PASS' if ok else 'FAIL'} {name}: {why}", flush=True) + if not ok: + failed.append(name) + print("Test Passed" if not failed else f"Test Failed: {failed}") + sys.exit(1 if failed else 0)