diff --git a/.github/workflows/pytorchsim_test.yml b/.github/workflows/pytorchsim_test.yml index fa45e3ddb..02a7f5490 100644 --- a/.github/workflows/pytorchsim_test.yml +++ b/.github/workflows/pytorchsim_test.yml @@ -72,6 +72,7 @@ jobs: - tests/ops/misc/test_user_triton_kernel.py - tests/ops/misc/test_widen_dtype.py - tests/ops/reduce/test_batchnorm.py + - tests/ops/sort/test_topk.py - tests/ops/view/test_view3D_2D.py - tests/system/test_compiler_failure.py - tests/system/test_eager.py diff --git a/pytorchsim/frontend/inductor_patches.py b/pytorchsim/frontend/inductor_patches.py index f79869ed9..121c63927 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, topk attention.install() + topk.install() inductor_config.max_autotune_gemm = True inductor_config.max_autotune_gemm_backends = "ATEN,TRITON" diff --git a/pytorchsim/frontend/rewrite_fx_graph.py b/pytorchsim/frontend/rewrite_fx_graph.py index f146ff23c..e78b7c016 100644 --- a/pytorchsim/frontend/rewrite_fx_graph.py +++ b/pytorchsim/frontend/rewrite_fx_graph.py @@ -1,11 +1,9 @@ """Our rewrites of the FX graph, so ops with no npu kernel stay on the device. -Decompositions (histc, polar) and post-grad passes (grouped_mm, topk, complex to -real pairs), all chained onto Inductor's one post-grad hook by install(). +Decompositions (histc, polar) and post-grad passes (grouped_mm, row mm, complex to real +pairs), all chained onto Inductor's one post-grad hook by install(). topk is frontend/topk.py. """ -from operator import getitem - import torch from torch import fx from torch._inductor.custom_graph_pass import CustomGraphPass @@ -177,74 +175,6 @@ def rewrite_grouped_mm(g) -> None: _recompile(g) -def _spent(dtype, largest): - """The value a taken element is replaced with, so it cannot win again.""" - info = torch.finfo(dtype) if dtype.is_floating_point else torch.iinfo(dtype) - return info.min if largest else info.max - - -def _emit_topk(g, x, k, dim, largest, shape, dtype, dev): - """Emit k rounds of max-and-mask and return the (values, indices) nodes.""" - call = g.call_function - i64 = torch.int64 - n = int(shape[dim]) - seat_shape = [1] * len(shape) - seat_shape[dim] = n - - rows = call(prims.iota.default, (n,), - {"start": 0, "step": 1, "dtype": i64, "device": dev, - "requires_grad": False}) - ar = call(aten.view.default, (rows, seat_shape)) - seat = call(aten.expand.default, (ar, list(shape))) - late = call(aten.full.default, (list(shape), n), {"dtype": i64, "device": dev}) - gone = call(aten.full.default, (list(shape), _spent(dtype, largest)), - {"dtype": dtype, "device": dev}) - - work, vals, idxs = x, [], [] - for _ in range(k): - best = call(aten.amax.default if largest else aten.amin.default, - (work, [dim], True)) - cand = call(aten.where.self, (call(aten.eq.Tensor, (work, best)), - seat, late)) - where = call(aten.amin.default, (cand, [dim], True)) - vals.append(best) - idxs.append(where) - work = call(aten.where.self, - (call(aten.eq.Tensor, (ar, where)), gone, work)) - return call(aten.cat.default, (vals, dim)), call(aten.cat.default, (idxs, dim)) - - -def rewrite_topk(g) -> None: - """Replace every `aten.topk.default` whose users are getitem with the rounds.""" - if isinstance(g, fx.GraphModule): - g = g.graph - changed = 0 - for node in list(g.nodes): - if node.op != "call_function" or node.target is not aten.topk.default: - continue - users = list(node.users) - if any(u.op != "call_function" or u.target is not getitem for u in users): - continue - x = node.args[0] - xv = x.meta.get("val") if hasattr(x, "meta") else None - if xv is None or xv.dim() == 0 or not xv.numel(): - continue - k = int(node.args[1]) - dim = int(node.args[2]) if len(node.args) > 2 else -1 - dim = dim if dim >= 0 else dim + xv.dim() - largest = bool(node.args[3]) if len(node.args) > 3 else True - if k < 1 or k > int(xv.shape[dim]): - continue - with g.inserting_before(node): - values, indices = _emit_topk(g, x, k, dim, largest, list(xv.shape), - xv.dtype, xv.device) - for u in users: - u.replace_all_uses_with(values if u.args[1] == 0 else indices) - changed += 1 - if changed: - _recompile(g) - - def _row_times_matrix(node): """(a, b, bias) of an mm or a plain addmm whose left operand is one row, else None.""" if node.op != "call_function": @@ -399,6 +329,5 @@ def call(target, *args): def install(): """Chain the post-grad passes onto Inductor's hook, each at most once.""" install_once("pytorchsim-grouped-mm", npu_only(rewrite_grouped_mm)) - install_once("pytorchsim-topk", npu_only(rewrite_topk)) install_once("pytorchsim-row-mm", npu_only(rewrite_row_mm)) install_once(_COMPLEX_TO_REAL.uuid(), npu_only(_COMPLEX_TO_REAL)) diff --git a/pytorchsim/frontend/topk.py b/pytorchsim/frontend/topk.py new file mode 100644 index 000000000..f4bf9b914 --- /dev/null +++ b/pytorchsim/frontend/topk.py @@ -0,0 +1,182 @@ +"""topk on the npu: one Triton kernel where it takes the call, the same rounds as aten ops elsewhere. + +The kernel puts a row on each lane and runs K rounds of max (min), first index of it, and mask, +gathering the K values and indices of its rows in registers and storing each once, as a TPU +kernel would. `topk_plan` is the one place that decides whether it takes a call; a call it +declines runs the rounds as aten ops (Inductor's kernels), and says why. + +aten::topk's npu kernel is registered at AutogradPrivateUse1, so it runs when torch.compile traces +(and at PrivateUse1, where a call under inference_mode lands), and calls `torchsim::topk`, a +`triton_op` whose body launches the kernel through `wrap_triton`. Its backward scatters the values' +gradient to the indices, aten's own topk backward. Eagerly the op runs the rounds, since a Triton +kernel cannot launch on the npu outside a compiled graph. ROUTED counts the kernel's launches and +the eager calls. +""" + +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() + +#: The calls that ran each route: "kernel" launches, "rounds" eager calls; a trace is not a call. +ROUTED = {} + + +def _count(route): + ROUTED[route] = ROUTED.get(route, 0) + 1 + + +@triton.jit +def _topk_kernel(x_ptr, v_ptr, i_ptr, rows, E: tl.constexpr, EP: tl.constexpr, K: tl.constexpr, + KP: tl.constexpr, XBLOCK: tl.constexpr, LARGEST: tl.constexpr): + r = tl.program_id(0) * XBLOCK + tl.arange(0, XBLOCK)[:, None] + c = tl.arange(0, EP)[None, :] + j = tl.arange(0, KP)[None, :] + live = r < rows + if LARGEST: + spent = float("-inf") + else: + spent = float("inf") + x = tl.load(x_ptr + r * E + c, mask=live & (c < E), other=spent) + vals = tl.zeros([XBLOCK, KP], dtype=x.dtype) + idxs = tl.zeros([XBLOCK, KP], dtype=tl.int32) + for n in tl.static_range(K): + if LARGEST: + best = tl.max(x, axis=1)[:, None] + else: + best = tl.min(x, axis=1)[:, None] + at = tl.min(tl.where(x == best, c, EP), axis=1)[:, None] + vals = tl.where(j == n, best, vals) + idxs = tl.where(j == n, at, idxs) + x = tl.where(c == at, spent, x) + out = live & (j < K) + tl.store(v_ptr + r * K + j, vals, mask=out) + tl.store(i_ptr + r * K + j, idxs.to(tl.int64), mask=out) + + +def _p2(n): + return 1 << max(0, (int(n) - 1).bit_length()) + + +def _tiles(xblock, ep, kp, esize): + """The tiles one program of _topk_kernel holds: the row and its masked copy, the index + candidates, and the gathered values and int64 indices.""" + return [(xblock, ep, esize), (xblock, ep, esize), (xblock, ep, 4), (xblock, kp, esize), + (xblock, kp, 8)] + + +def topk_plan(x, k, dim): + """(the kernel's blocks, None) when it takes topk of `x` along `dim`, else (None, why). A + program takes a row on each lane, those past the last masked, halved while its tiles overrun + the scratchpad budget.""" + from pytorchsim.frontend.attention import _fits + if not x.is_floating_point(): + return None, f"{x.dtype} is not a floating dtype" + if x.dim() == 0 or x.numel() == 0: + return None, "an empty or 0-d input" + if dim != x.dim() - 1: + return None, f"dim {dim} is not the last of {x.dim()}" + E = int(x.shape[-1]) + ep, kp = _p2(E), _p2(k) + xblock = int(config.CONFIG_MACHINE.vector_lanes) + while xblock > 1 and not _fits(_tiles(xblock, ep, kp, x.dtype.itemsize)): + xblock //= 2 + if not _fits(_tiles(xblock, ep, kp, x.dtype.itemsize)): + return None, f"a row of {E} overruns the scratchpad budget" + return {"XBLOCK": xblock, "EP": ep, "KP": kp}, None + + +def _spent(dtype, largest): + """The value a taken element is replaced with, so it cannot win again.""" + info = torch.finfo(dtype) if dtype.is_floating_point else torch.iinfo(dtype) + return info.min if largest else info.max + + +def _rounds(x, k, dim, largest): + """The kernel's rounds as aten ops: (values, int64 indices), the first index of each best.""" + if x.dim() == 0: + v, i = _rounds(x.view(1), k, 0, largest) + return v.view(x.shape[:0] if k else (0,)), i.view(x.shape[:0] if k else (0,)) + if k == 0: + shape = [*x.shape[:dim], 0, *x.shape[dim + 1:]] + return x.new_empty(shape), x.new_empty(shape, dtype=torch.int64) + n = int(x.shape[dim]) + seat_t = torch.int32 if n < 2**31 else torch.int64 + shape = [1] * x.dim() + shape[dim] = n + ar = torch.arange(n, dtype=seat_t, device=x.device).view(shape) + seat = ar.expand(x.shape) + late = torch.full(x.shape, n, dtype=seat_t, device=x.device) + gone = torch.full(x.shape, _spent(x.dtype, largest), dtype=x.dtype, device=x.device) + work, vals, idxs = x, [], [] + for _ in range(k): + best = work.amax(dim, keepdim=True) if largest else work.amin(dim, keepdim=True) + where = torch.where(work == best, seat, late).amin(dim, keepdim=True) + vals.append(best) + idxs.append(where.to(torch.int64)) + work = torch.where(ar == where, gone, work) + return torch.cat(vals, dim), torch.cat(idxs, dim) + + +@triton_op("torchsim::topk", mutates_args=()) +def topk(x: torch.Tensor, k: int, dim: int, largest: bool) -> tuple[torch.Tensor, torch.Tensor]: + """topk of `x` along `dim` (non-negative), sorted, as a compiled graph sees it: the kernel + where topk_plan takes it, else the rounds. The kernel's arguments are passed by position.""" + plan, why = topk_plan(x, k, dim) + if plan is None: + logger.info("topk on the npu runs the rounds as aten ops, not the kernel: x %s %s k=%d " + "dim=%d (%s)", tuple(x.shape), x.dtype, k, dim, why) + return _rounds(x, k, dim, largest) + xc = x.contiguous() + E = int(x.shape[-1]) + rows = x.numel() // E + v = torch.empty(*x.shape[:-1], k, dtype=x.dtype, device=x.device) + i = torch.empty(*x.shape[:-1], k, dtype=torch.int64, device=x.device) + wrap_triton(_topk_kernel)[(triton.cdiv(rows, plan["XBLOCK"]), 1, 1)]( + xc, v, i, rows, E, plan["EP"], k, plan["KP"], plan["XBLOCK"], largest) + return v, i + + +@topk.register_kernel("npu") +def _topk_eager(x, k, dim, largest): + _count("rounds") + return _rounds(x, k, dim, largest) + + +def _setup_backward(ctx, inputs, output): + x, _, dim, _ = inputs + ctx.dim, ctx.shape = dim, x.shape + ctx.save_for_backward(output[1]) + + +def _backward(ctx, grad_values, grad_indices): + (indices,) = ctx.saved_tensors + grad = grad_values.new_zeros(ctx.shape).scatter(ctx.dim, indices, grad_values) + return grad, None, None, None + + +topk.register_autograd(_backward, setup_context=_setup_backward) + + +def _aten_topk(x, k, dim=-1, largest=True, sorted=True): + """aten::topk on the npu: torchsim::topk with a non-negative dim; its values are sorted.""" + return topk(x, int(k), dim % max(x.dim(), 1), bool(largest)) + + +_lib = None + + +def install(): + """Register aten::topk's npu kernel above autograd and functionalization, and at the backend + key, where a call made under inference_mode lands. Count each kernel launch.""" + global _lib + if _lib is None: + from pytorchsim.driver import codecache + codecache.observe_launches(_topk_kernel, lambda: _count("kernel")) + _lib = torch.library.Library("aten", "IMPL") + for key in ("AutogradPrivateUse1", "PrivateUse1"): + _lib.impl("topk", _aten_topk, key) diff --git a/scripts/ci/triton_route_passing.txt b/scripts/ci/triton_route_passing.txt index d12367bd4..edd58c1df 100644 --- a/scripts/ci/triton_route_passing.txt +++ b/scripts/ci/triton_route_passing.txt @@ -272,6 +272,7 @@ tests/ops/misc/test_polar.py tests/ops/misc/test_user_triton_kernel.py tests/ops/misc/test_widen_dtype.py tests/ops/reduce/test_batchnorm.py +tests/ops/sort/test_topk.py tests/ops/view/test_view3D_2D.py tests/system/test_eager.py tests/system/test_patch_scope.py diff --git a/tests/ops/sort/test_topk.py b/tests/ops/sort/test_topk.py index e27c199db..ba75b7bfb 100644 --- a/tests/ops/sort/test_topk.py +++ b/tests/ops/sort/test_topk.py @@ -1,30 +1,126 @@ +"""torch.topk on the npu: the topk kernel where topk.topk_plan takes the call, the rounds as aten ops +where it does not, against torch.topk on the CPU. + +Each case states the route it must take and checks topk.ROUTED: one "kernel" count per launch of a +compiled call the kernel takes, one "rounds" count per eager call, nothing for rounds compiled into +the graph (Inductor's own kernels). Ties take the first index, as a stable descending sort does. + + kernel rows a whole number of programs and not, a row length that is not a power of two, the + smallest k, bf16, ties + rounds topk along a dim that is not the last + grad a compiled call whose input requires grad runs the kernel, and its gradient is aten's + eager outside torch.compile, and under inference_mode eagerly and compiled + counts a compiled call run twice counts two launches, not its traces + +Usage: test_topk.py [case ...] (all cases when none is named) +""" import os import sys + import torch -import torch._dynamo -import torch.utils.cpp_extension -sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result -def test_topk(device, size=(128, 128), k=5, dim=-1, largest=True, sorted=True): - # dim 해석을 위해 양수 인덱스로 변환 - dim_ = dim if dim >= 0 else (len(size) + dim) - assert 0 <= dim_ < len(size), "dim이 텐서 차원 범위를 벗어났습니다." - assert k <= size[dim_], f"k(={k})는 size[dim](={size[dim_]}) 이하여야 합니다." +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), + "tests")) + +device = torch.device("npu:0") + +# name: (route, shape, k, dim, largest, dtype) +CASES = { + "router": ("kernel", (64, 128), 8, -1, True, torch.float32), + "ragged_rows": ("kernel", (100, 128), 5, -1, True, torch.float32), + "row_not_pow2": ("kernel", (32, 100), 3, -1, True, torch.float32), + "smallest": ("kernel", (64, 128), 4, -1, False, torch.float32), + "bf16": ("kernel", (64, 128), 8, -1, True, torch.bfloat16), + "ties": ("kernel", (64, 128), 8, -1, True, torch.float32), + "dim0": ("rounds", (128, 32), 4, 0, True, torch.float32), +} + + +def _input(shape, dtype, ties=False, seed=0): + g = torch.Generator().manual_seed(seed) + x = torch.randn(*shape, generator=g) + return ((x * 4).round() if ties else x).to(dtype) + + +def _ref(x, k, dim, largest): + """Values and indices of a stable sort: among equal values the first index comes first.""" + order = torch.sort(x.float(), dim=dim, descending=largest, stable=True).indices.narrow(dim, 0, k) + return x.gather(dim, order), order + + +def _routed(): + from pytorchsim.frontend import topk + return topk.ROUTED + + +def _check(name, got, want, route, took): + """Values and indices equal, and ROUTED is `route` (a dict of counts).""" + ok = torch.equal(got[0].cpu(), want[0]) and torch.equal(got[1].cpu(), want[1]) and took == route + print(f"{name}: route={took} want={route} {'PASS' if ok else 'FAIL'}", flush=True) + return ok + + +def run_case(name): + route, shape, k, dim, largest, dtype = CASES[name] + x = _input(shape, dtype, ties=name == "ties") + _routed().clear() + torch._dynamo.reset() + f = torch.compile(lambda t: torch.topk(t, k, dim=dim, largest=largest), dynamic=False) + want = {} if route == "rounds" else {route: 1} + return _check(name, f(x.to(device)), _ref(x, k, dim, largest), want, dict(_routed())) + + +def run_grad(name): + """values.sum().backward() through the compiled kernel: the gradient is 1 at each index taken.""" + x = _input((64, 128), torch.float32) + ref = x.clone().requires_grad_() + torch.topk(ref, 8, -1).values.sum().backward() + dev = x.to(device).requires_grad_() + _routed().clear() + torch._dynamo.reset() + v, i = torch.compile(lambda t: torch.topk(t, 8, -1), dynamic=False)(dev) + v.sum().backward() + ok = torch.equal(dev.grad.cpu(), ref.grad) and dict(_routed()) == {"kernel": 1} + print(f"{name}: route={dict(_routed())} want=kernel {'PASS' if ok else 'FAIL'}", flush=True) + return ok + + +def run_eager(name): + """Outside torch.compile the rounds run (one count); compiled under inference_mode, the kernel.""" + x = _input((64, 128), torch.float32) + want = _ref(x, 8, -1, True) + _routed().clear() + torch._dynamo.reset() + compiled = name == "inference_mode_compiled" + f = (torch.compile(lambda t: torch.topk(t, 8, -1), dynamic=False) if compiled + else lambda t: torch.topk(t, 8, -1)) + ctx = torch.no_grad() if name == "eager" else torch.inference_mode() + with ctx: + got = f(x.to(device)) + return _check(name, got, want, {"kernel": 1} if compiled else {"rounds": 1}, dict(_routed())) + - def topk_fn(a): - return torch.topk(a, k, dim=dim, largest=largest, sorted=sorted) +def run_counts(name): + """A compiled call run twice counts two launches.""" + x = _input((64, 128), torch.float32) + _routed().clear() + torch._dynamo.reset() + f = torch.compile(lambda t: torch.topk(t, 8, -1), dynamic=False) + for _ in range(2): + f(x.to(device)) + ok = dict(_routed()) == {"kernel": 2} + print(f"{name}: route={dict(_routed())} want={{'kernel': 2}} {'PASS' if ok else 'FAIL'}", + flush=True) + return ok - x = torch.randn(size) - x = x.to(device=device) - opt_topk = torch.compile(dynamic=False)(topk_fn) - res_values, res_indices = opt_topk(x) - ref_values, ref_indices = torch.topk(x.cpu(), k, dim=dim, largest=largest, sorted=sorted) +EXTRA = {"grad": run_grad, "eager": run_eager, "inference_mode": run_eager, + "inference_mode_compiled": run_eager, "counts": run_counts} - test_result("TopK/values", res_values, ref_values) - test_result("TopK/indices", res_indices, ref_indices) if __name__ == "__main__": - device = torch.device('npu:0') - test_topk(device, (128, 128), k=2, dim=-1) \ No newline at end of file + names = sys.argv[1:] or [*CASES, *EXTRA] + results = [EXTRA[n](n) if n in EXTRA else run_case(n) for n in names] + if not all(results): + sys.exit(1) + print("PASS")