diff --git a/.github/workflows/pytorchsim_test.yml b/.github/workflows/pytorchsim_test.yml index 58dce160..1a136798 100644 --- a/.github/workflows/pytorchsim_test.yml +++ b/.github/workflows/pytorchsim_test.yml @@ -17,9 +17,9 @@ on: # --preset) runs here once without arguments, which runs the same presets in one process, and # tests/system tests the allowlist leaves out run here too: test_compiler_failure, # test_reduction_tiling and test_select, and test_autotune_tables, test_breakdown_viewer, -# test_device_interface, test_launch_dir, test_module_form, test_npuwattch_json, test_one_layer_kv_write, -# test_one_layer_mask, test_one_layer_softcap_mask, test_patch_scope, test_route_allowlist, test_togsim_exit, -# test_togsim_result and test_verify_golden, which emit no kernel and so are no route coverage. +# test_device_interface, test_launch_dir, test_module_form, test_npuwattch_json, test_on_chip, +# test_one_layer_kv_write, test_one_layer_mask, test_one_layer_softcap_mask, test_patch_scope, test_route_allowlist, +# test_togsim_exit, test_togsim_result and test_verify_golden, which emit no kernel and so are no route coverage. # Regenerate the allowlist with # python scripts/ci/triton_route_sweep.py --all --update-allowlist # and mirror its files here; a test absent from both is not gated anywhere. @@ -71,7 +71,10 @@ jobs: - 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_int_mm.py - tests/ops/gemm/test_row_matmul.py + - tests/ops/gemm/test_w8a8_linear.py + - tests/ops/gemm/test_widened_weight_mm.py - tests/ops/gemm/test_zero_length_gemm.py - tests/ops/misc/test_complex_to_real.py - tests/ops/misc/test_custom_fused_kernel.py @@ -98,6 +101,7 @@ jobs: - tests/system/test_launch_record.py - tests/system/test_module_form.py - tests/system/test_npuwattch_json.py + - tests/system/test_on_chip.py - tests/system/test_one_layer_kv_write.py - tests/system/test_one_layer_mask.py - tests/system/test_one_layer_softcap_mask.py diff --git a/docker/Dockerfile.base b/docker/Dockerfile.base index 03d9b0b3..82341eb8 100644 --- a/docker/Dockerfile.base +++ b/docker/Dockerfile.base @@ -23,7 +23,7 @@ RUN python3.11 -m pip install --no-cache-dir \ # torchsim backend linked in; a pip triton would shadow nothing but confuse `import triton`. RUN python3.11 -m pip install --no-cache-dir \ numpy==2.4.6 matplotlib scikit-learn \ - transformers==5.15.0 diffusers==0.34.0 \ + transformers==5.15.0 diffusers==0.37.1 torchao==0.18.0 \ cmake==3.26.4 && \ python3.11 -m pip install --no-cache-dir --no-deps ultralytics && \ python3.11 -m pip install --no-cache-dir opencv-python-headless pandas seaborn \ diff --git a/pytorchsim/backend/compiler_input.py b/pytorchsim/backend/compiler_input.py index 280f945e..22c7a9ca 100644 --- a/pytorchsim/backend/compiler_input.py +++ b/pytorchsim/backend/compiler_input.py @@ -82,6 +82,7 @@ def reference(inputs): grid={grid!r}, parallel_axes={parallel_axes!r}, graph_prefetch={graph_prefetch!r}, + on_chip={on_chip!r}, reference=reference, make_inputs=make_inputs, extra={{"scalar_args": {scalar_decls!r}, @@ -121,6 +122,15 @@ def graph_prefetch(meta): return tuple(sorted(names.index(n) for n in meta["graph_prefetch"])) +def on_chip(meta): + """The spec's on_chip: the tensor indices of the arguments meta's on_chip names.""" + names = parameter_names(meta) + unknown = sorted(set(meta.get("on_chip", ())) - set(names)) + if unknown: + raise SpecIncomplete(f"{meta['kernel_name']}: on_chip names {unknown}, no parameter of it") + return tuple(sorted(names.index(n) for n in meta.get("on_chip", ()))) + + def recorded_file(kernel_name): """The file beside a kernel file holding the launch values of the args it does not draw.""" return f"{kernel_name}_inputs.pt" @@ -174,6 +184,7 @@ def write(src_code, meta, path, recorded=None, scalars=None): grid=contract.grid_xyz(meta), parallel_axes=tuple(contract.launch_axes(meta)), graph_prefetch=graph_prefetch(meta), + on_chip=on_chip(meta), scalar_decls=[(n, c) for n, c, _ in scalars], scalar_values={n: v if v is not None else given[n] for n, _, v in scalars if v is not None or n in given}, ) @@ -198,7 +209,7 @@ def spec_json(meta): [(a["role"], a["numel"], _UNSIGNED.get(a.get("dtype"))) for a in meta["args"]], contract.grid_xyz(meta), list(graph_prefetch(meta)), list(contract.launch_axes(meta)), {"scalar_args": [[n, c] for n, c, _ in scalars], - "scalar_values": {n: v for n, _, v in scalars if v is not None}})) + "scalar_values": {n: v for n, _, v in scalars if v is not None}}, on_chip(meta))) def backend_options(spec): @@ -213,12 +224,14 @@ def backend_options(spec): """The dtypes a spec must state: Triton IR spells an unsigned pointer as its signed width (!tt.ptr).""" -def spec_dict(tensors, grid, held=(), axes=("x",), extra=None): +def spec_dict(tensors, grid, held=(), axes=("x",), extra=None, on_chip=()): """A JSON spec: `tensors` as (role, numel[, dtype]) per pointer parameter in order (a dtype only where the IR - cannot say it), the default launch `grid`, the tensor indices held, the axes the launch spreads over.""" + cannot say it), the default launch `grid`, the tensor indices held, the axes the launch spreads over, and + the tensor indices the graph keeps on chip (stated only when there are any).""" return {"args": [dict({"role": t[0], "shape": [t[1]]}, **({"dtype": t[2]} if len(t) > 2 and t[2] else {})) for t in tensors], "grid": list(grid), "grid_rule": True, - "graph_prefetch": list(held), "parallel_axes": list(axes), "extra": extra or {}} + "graph_prefetch": list(held), "parallel_axes": list(axes), "extra": extra or {}, + **({"on_chip": list(on_chip)} if on_chip else {})} META_JSON = "meta.json" diff --git a/pytorchsim/contract.py b/pytorchsim/contract.py index 149d41ab..66454d12 100644 --- a/pytorchsim/contract.py +++ b/pytorchsim/contract.py @@ -107,7 +107,7 @@ def storage_span(size, stride, offset=0): KERNEL_MANIFEST = "kernel.json" -KERNEL_FORMAT = 10 +KERNEL_FORMAT = 11 def kernel_object(workdir): diff --git a/pytorchsim/frontend/inductor/autotune/__init__.py b/pytorchsim/frontend/inductor/autotune/__init__.py index eb02002f..ca74b024 100644 --- a/pytorchsim/frontend/inductor/autotune/__init__.py +++ b/pytorchsim/frontend/inductor/autotune/__init__.py @@ -4,6 +4,7 @@ template_kernel_selection.py which offered config a template kernel takes generated_kernel_blocks.py any other kernel's blocks, pinned from the machine; its reductions' persistence, split graph_prefetch.py which graph input the graph holds resident, and which kernel states it + on_chip.py which intermediates the graph keeps in the scratchpad, and which kernels state them """ diff --git a/pytorchsim/frontend/inductor/autotune/graph_prefetch.py b/pytorchsim/frontend/inductor/autotune/graph_prefetch.py index 501f2c26..2108462d 100644 --- a/pytorchsim/frontend/inductor/autotune/graph_prefetch.py +++ b/pytorchsim/frontend/inductor/autotune/graph_prefetch.py @@ -63,8 +63,17 @@ def fits(node): shape, size = (contract.storage_span(sizes(val.shape), sizes(val.stride())),), val.dtype.itemsize if cn.resident_fits(target, shape, size): return None - return (f"{cn.resident_lane_bytes(target, shape, size)} bytes a lane held whole, over " - f"{cn.resident_budget(target)}") + return f"{lane_bytes(node)} bytes a lane held whole, over {cn.resident_budget(target)}" + + +def lane_bytes(node): + """A lane's bytes of the tensor FX node `node` makes held whole (contract/copy_node.resident_lane_bytes), + as the kernel spec states it: its storage span.""" + from pytorchsim.backend import compiler_bridge + val = node.meta["val"] + return compiler_bridge.compiler_contract("copy_node").resident_lane_bytes( + compiler_bridge.target(), (contract.storage_span(sizes(val.shape), sizes(val.stride())),), + val.dtype.itemsize) def elected(graph): diff --git a/pytorchsim/frontend/inductor/autotune/mm_resident.py b/pytorchsim/frontend/inductor/autotune/mm_resident.py index 78d2bbe5..b528415e 100644 --- a/pytorchsim/frontend/inductor/autotune/mm_resident.py +++ b/pytorchsim/frontend/inductor/autotune/mm_resident.py @@ -94,8 +94,9 @@ def blocks(m, n, k, got): def templates_for(kernel_inputs, templates, op_name): - """`templates` for one npu mm or addmm: only the resident mm where it holds the graph's prefetch - (decline), else as offered; the decision and why are logged.""" + """`templates` for one npu mm or addmm: the resident mm where it holds the graph's prefetch (decline), + with the mm template beside it when the streamed operand is widened from a narrower dtype (the mm template + can load it narrow and widen it in place), else as offered; the decision and why are logged.""" from torch._inductor.kernel.mm import mm_template if op_name not in GEMMS or kernel_inputs.device_type != "npu" or mm_template not in templates: return templates @@ -103,10 +104,30 @@ def templates_for(kernel_inputs, templates, op_name): if why is not None: logger.info("[mm_resident] %s: the mm template, %s", _label(kernel_inputs), why) return templates + if _widened(kernel_inputs.mat1mat2()[1 - got.resident]): + logger.info("[mm_resident] %s: %s; the mm template too, the streamed operand widened", + _label(kernel_inputs), got.why) + return [mm_resident_template, mm_template] logger.info("[mm_resident] %s: %s", _label(kernel_inputs), got.why) return [mm_resident_template] +def _widened(node): + """Whether `node` is computed elementwise from buffers all of a narrower dtype, as an int8 weight widened + to bf16 is: a prologue the mm template takes, which the resident mm, loading its operands raw, does not.""" + from torch._inductor import ir + from torch._inductor.virtualized import V + try: + buf = V.graph.get_buffer(node.get_name()) + except (AttributeError, NotImplementedError): + return False + if not isinstance(buf, ir.ComputedBuffer) or not isinstance(buf.data, ir.Pointwise): + return False + reads = buf.get_read_names() + size = buf.get_dtype().itemsize + return bool(reads) and all(V.graph.get_dtype(r).itemsize < size for r in reads) + + def decline(kernel_inputs): """(why the resident mm does not take this GEMM, or None; its Plan): where copy_node.plan holds one, it holds the graph's prefetch (graph_prefetch.held_operand), streaming the other by best_tile.""" diff --git a/pytorchsim/frontend/inductor/autotune/on_chip.py b/pytorchsim/frontend/inductor/autotune/on_chip.py new file mode 100644 index 00000000..c985e62a --- /dev/null +++ b/pytorchsim/frontend/inductor/autotune/on_chip.py @@ -0,0 +1,78 @@ +"""A graph's intermediates kept in the scratchpad, as v6e XLA keeps a W8A8 Linear's int8 activation in VMEM (memory +space S(1)) for the matmul fusion that reads it: a tensor a kernel makes, every use of which (through views) is a +matmul operand, stays on chip from its maker to its last reader where it fits beside the others kept with it.""" + +import weakref + +import torch + +from pytorchsim import config +from . import graph_prefetch + +logger = config.setup_logger() + +READERS = {**graph_prefetch.MATMULS, torch.ops.aten._int_mm.default: (0, 1)} + +_ELECTED = weakref.WeakKeyDictionary() + + +def elected(graph): + """{FX node: (a lane's bytes, its position, its last reader's)} of one lowering: in graph order each node + every use of which is a matmul operand (`readers`), kept where it fits copy_node.resident_budget beside the + graph's resident inputs and the nodes kept over its life; once per graph, each skip logged.""" + if graph in _ELECTED: + return _ELECTED[graph] + from pytorchsim.backend import compiler_bridge + fx = graph.module.graph + position = {n: i for i, n in enumerate(fx.nodes)} + held = graph_prefetch.elected(graph) + budget = compiler_bridge.compiler_contract("copy_node").resident_budget(compiler_bridge.target()) - sum( + graph_prefetch.lane_bytes(n) for n in fx.find_nodes(op="placeholder") if n.target in held) + kept = {} + for node in fx.nodes: + if node.op != "call_function" or node.target in graph_prefetch.VIEWS: + continue + got, why = readers(node) + if why is not None or not got: + continue + need, start, end = graph_prefetch.lane_bytes(node), position[node], max(position[u] for u in got) + beside = sum(b for b, s, e in kept.values() if s <= end and e >= start) + if beside + need > budget: + logger.info("[on_chip] %s: not kept, %d bytes a lane beside %d of %d", node, need, beside, budget) + continue + kept[node] = (need, start, end) + logger.info("[on_chip] the graph keeps %s", sorted(map(str, kept)) or "nothing") + _ELECTED[graph] = kept + return kept + + +def readers(node): + """([the matmuls reading `node` through views], the first use that is no matmul operand or None).""" + got = [] + for user in node.users: + at = [i for i, a in enumerate(user.args) if a is node] + if user.target in graph_prefetch.VIEWS and at == [0] and not user.kwargs: + sub, why = readers(user) + if why is not None: + return got, why + got += sub + elif user.target in READERS and at and set(at) <= set(READERS[user.target]): + got.append(user) + else: + return got, f"used by {user.target} (args {at})" + return got, None + + +def statement(args): + """The names of `args` (a kernel's meta args) whose buffer holds a node the graph keeps on chip: an output + its kernel leaves there, an input its kernel reads there.""" + from torch._inductor.virtualized import V + kept = elected(V.graph) + if not kept: + return [] + out = [] + for a in args: + buf = V.graph.name_to_buffer.get(a.get("buffer")) + if buf is not None and buf.get_origin_node() in kept: + out.append(a["name"]) + return out diff --git a/pytorchsim/frontend/inductor/codegen/kernel_metadata.py b/pytorchsim/frontend/inductor/codegen/kernel_metadata.py index 57c655bd..3679265f 100644 --- a/pytorchsim/frontend/inductor/codegen/kernel_metadata.py +++ b/pytorchsim/frontend/inductor/codegen/kernel_metadata.py @@ -1,6 +1,6 @@ """What the compile step needs from an Inductor kernel, read while `V.graph` is live: collect_meta gathers the arguments with their roles, dtypes and storage spans, the numels, the pinned blocks and the grid; -define_kernel adds what it holds (graph_prefetch), none until then.""" +define_kernel adds what it holds (graph_prefetch, on_chip), none until then.""" from torch._inductor.codegen.common import InplacedBuffer, is_buffer_removed from torch._inductor.virtualized import V @@ -143,9 +143,10 @@ def _blocks_without_pin(kernel, numels, args): def spec_options(kernel, name): """The backend_options carrying `kernel`'s spec; its meta is kept as kernel._npu_meta.""" from pytorchsim.backend import compiler_input - from pytorchsim.frontend.inductor.autotune import graph_prefetch + from pytorchsim.frontend.inductor.autotune import graph_prefetch, on_chip meta = collect_meta(kernel, name) meta["graph_prefetch"] = graph_prefetch.statement(kernel, meta["args"]) + meta["on_chip"] = on_chip.statement(meta["args"]) kernel._npu_meta = meta return compiler_input.backend_options(compiler_input.spec_json(meta)) @@ -208,6 +209,7 @@ def collect_meta(kernel, kernel_name): "fixed_config": _held_blocks(kernel) or _blocks_without_pin(kernel, numels, args), "template_grid": template_grid(kernel), "graph_prefetch": [], + "on_chip": [], } @@ -244,6 +246,7 @@ def benchmark_request_meta(req): "fixed_config": tiling.fixed_config_for(None, numels, args), "template_grid": [int(g) for g in req.extra_args], "graph_prefetch": [], + "on_chip": [], } diff --git a/pytorchsim/frontend/inductor/codegen/scheduling.py b/pytorchsim/frontend/inductor/codegen/scheduling.py index c9579497..3693783a 100644 --- a/pytorchsim/frontend/inductor/codegen/scheduling.py +++ b/pytorchsim/frontend/inductor/codegen/scheduling.py @@ -11,7 +11,7 @@ from pytorchsim import config from pytorchsim.backend import compiler_input -from pytorchsim.frontend.inductor.autotune import generated_kernel_blocks, graph_prefetch +from pytorchsim.frontend.inductor.autotune import generated_kernel_blocks, graph_prefetch, on_chip from pytorchsim.frontend.inductor.autotune.generated_kernel_configs import CANDIDATES_KEY from pytorchsim.frontend.inductor.codegen import kernel_metadata @@ -108,6 +108,7 @@ def generate_kernel_code_from_nodes(self, nodes, benchmark_kernel=False, hint_ov kernel = self._codegen_kernel meta = kernel_metadata.collect_meta(kernel, "triton_") meta["graph_prefetch"] = graph_prefetch.statement(kernel, meta["args"]) + meta["on_chip"] = on_chip.statement(meta["args"]) self._benchmarked[PyCodeCache.write(src_code)[1]] = (src_code, meta) return src_code diff --git a/pytorchsim/frontend/inductor/codegen/user_kernel.py b/pytorchsim/frontend/inductor/codegen/user_kernel.py index 1ace0ddc..52588048 100644 --- a/pytorchsim/frontend/inductor/codegen/user_kernel.py +++ b/pytorchsim/frontend/inductor/codegen/user_kernel.py @@ -97,7 +97,7 @@ def user_kernel_meta(kernel, kwargs, triton_meta, grid): where torch's mutation analysis says the launch writes it (every pointer, without that analysis).""" from pytorchsim.contract import storage_span from pytorchsim.backend.launch_hooks import user_kernel_id - from pytorchsim.frontend.inductor.autotune import graph_prefetch + from pytorchsim.frontend.inductor.autotune import graph_prefetch, on_chip from pytorchsim.frontend.inductor.codegen import kernel_metadata hint = V.graph.sizevars.optimization_hint @@ -128,4 +128,5 @@ def user_kernel_meta(kernel, kwargs, triton_meta, grid): "template_grid": ([int(hint(g)) for g in grid] + [1, 1, 1])[:3], "user_defined": True, "user_kernel": user_kernel_id(kernel), "graph_prefetch": graph_prefetch.statement(kernel, args), + "on_chip": on_chip.statement(args), } diff --git a/pytorchsim/frontend/inductor/postgrad/__init__.py b/pytorchsim/frontend/inductor/postgrad/__init__.py index d2c218d8..e984b8b9 100644 --- a/pytorchsim/frontend/inductor/postgrad/__init__.py +++ b/pytorchsim/frontend/inductor/postgrad/__init__.py @@ -4,6 +4,9 @@ histc.py histc aten.histc counted on the device gemm.py mm_row, addmm_row a 1 x K row times a matrix as a multiply and a sum: vector work gemm_zero_length a matmul with an empty output, or K = 0 and no bias, as zeros + int_mm an int8 matmul widened to int32 as aten._int_mm: the mm template; + a 1 x K row as mm_row's vector work, summed in int32 + mm_widened_weight an mm's right operand widened from a narrower dtype, row-major convolution.py convolution_transposed a transposed conv as its direct equivalent convolution_1d a 1-D conv as a 2-D one over a height of 1 convolution_pointwise a 1x1 conv as [O, C] times the pixels: one mm, lanes on pixels diff --git a/pytorchsim/frontend/inductor/postgrad/gemm.py b/pytorchsim/frontend/inductor/postgrad/gemm.py index e241afbb..8074dd0d 100644 --- a/pytorchsim/frontend/inductor/postgrad/gemm.py +++ b/pytorchsim/frontend/inductor/postgrad/gemm.py @@ -1,4 +1,5 @@ -"""The matmul family: a row times a matrix as vector work, and matmuls with nothing to compute.""" +"""The matmul family: a row times a matrix as vector work, matmuls with nothing to compute, and int8 matmuls +widened to int32.""" import torch from torch import fx @@ -7,6 +8,7 @@ from pytorchsim.frontend.inductor.postgrad import fake_value, register_rewrite aten = torch.ops.aten +prims = torch.ops.prims # mm_row, addmm_row: a 1 x K row times a matrix @@ -19,18 +21,21 @@ def _is_row(match): and av.shape[0] == 1 and av.is_floating_point() and bv.is_floating_point()) -def _row_times(a, b): +def _row_times(a, b, acc=None): """The row stored first (a no-op when it already is), broadcast down the matrix, a multiply and a sum over - K: every block reads the stored row, where a row computed in the kernel is spread over the lanes per block.""" + K in `acc` when given (both operands widened to it): every block reads the stored row.""" from torch._inductor import inductor_prims - return (inductor_prims.force_stride_order(a, [a.shape[1], 1]).reshape(-1, 1) * b).sum(0, keepdim=True) + row = inductor_prims.force_stride_order(a, [a.shape[1], 1]).reshape(-1, 1) + if acc is not None: + row, b = row.to(acc), b.to(acc) + return (row * b).sum(0, keepdim=True, dtype=acc) @register_rewrite(CallFunction(aten.mm.default, Arg(), Arg()), _is_row) def mm_row(node, a, b): """A 1 x K row times a K x N matrix as _row_times: vector work, where the mm template would run it on the array.""" - return _row_times, [a, b] + return (lambda a, b: _row_times(a, b)), [a, b] @register_rewrite(CallFunction(aten.addmm.default, Arg(), Arg(), Arg()), _is_row) @@ -64,3 +69,46 @@ def gemm_zero_length(node, *args, **kwargs): for _op, _bias in ((aten.mm.default, 0), (aten.bmm.default, 0), (aten.addmm.default, 1), (aten.baddbmm.default, 1)): register_rewrite(CallFunctionVarArgs(_op), _is_zero_length(_bias))(gemm_zero_length) + + +# int_mm: an int8 matmul widened to int32 before an mm, as the int8 matmul it is + +def _widened(): + """A fresh pattern for one operand converted to int32 (the matcher binds a pattern to one node).""" + return CallFunction(prims.convert_element_type.default, Arg(), torch.int32) + + +def _is_int8_widened(match): + """Both operands of the int32 mm are 2-D int8 tensors widened to int32.""" + vals = [fake_value(a) for a in match.args] + return all(v is not None and v.dim() == 2 and v.dtype == torch.int8 for v in vals) + + +@register_rewrite(CallFunction(aten.mm.default, _widened(), _widened()), _is_int8_widened) +def int_mm(node, a, b): + """mm(a.to(int32), b.to(int32)) of int8 a and b as aten._int_mm(a, b) on the mm template, a 1 x K row as + _row_times summed in int32 (vector work, as mm_row): equal bit for bit to the int32 mm.""" + if fake_value(a).shape[0] == 1: + return (lambda a, b: _row_times(a, b, torch.int32)), [a, b] + return (lambda a, b: aten._int_mm(a, b)), [a, b] + + +# mm_widened_weight: an mm's right operand widened from a narrower dtype, stored row-major + +def _is_widened_strided(match): + """The right operand of a 2-D mm is a widening convert (int8 to bf16, say) whose result is not row-major, + as a transposed weight's is: its strides follow the narrow source.""" + a, conv = match.args[0], match.output_node().args[1] + src, wide = fake_value(conv.args[0]), fake_value(conv) + return (src is not None and wide is not None and fake_value(a) is not None and wide.dim() == 2 + and src.dtype.itemsize < wide.dtype.itemsize and not wide.is_contiguous()) + + +@register_rewrite(CallFunction(aten.mm.default, Arg(), CallFunction(prims.convert_element_type.default, Arg(), + Arg())), _is_widened_strided) +def mm_widened_weight(node, a, w, dtype): + """The widened right operand stored row-major (force_stride_order): the layout the mm template reads, so + it can load the narrow source and widen it in place, where a transposed one conflicts and has no fallback.""" + from torch._inductor import inductor_prims + n = fake_value(node).shape[1] + return (lambda a, w: torch.mm(a, inductor_prims.force_stride_order(w.to(dtype), [n, 1]))), [a, w] diff --git a/pytorchsim/frontend/inductor/registration.py b/pytorchsim/frontend/inductor/registration.py index fc2d4be2..d7fa7dbc 100644 --- a/pytorchsim/frontend/inductor/registration.py +++ b/pytorchsim/frontend/inductor/registration.py @@ -11,9 +11,14 @@ codegen heuristics the configs of a generated pointwise or reduction kernel, autotune/'s PTB's Triton driver the runner a launch goes to: Spike and TOGSim Inductor's benchmarker what picks one of a kernel's compiled configs + Inductor's decompositions npu's mm and bmm as with coordinate descent off (a patch: it has no hook) + Inductor's realize on reuse a row value a broadcast reads again computed once (a patch: it has no hook) + Inductor's node lowering an int8 matmul's dequantized result stored, its epilogue (a patch: it has no hook) + Inductor's template fusions each pending one benchmarked, though two compile one source (a patch: it has no hook) """ import functools +import weakref from textwrap import dedent import torch @@ -45,6 +50,10 @@ def install(): _register_codegen_heuristics() _register_launcher() _register_benchmarker() + _register_decompositions() + _register_realize_on_broadcast() + _register_realize_dequant() + _register_template_fusion_futures() # Dynamo's device interfaces (torch._dynamo.device_interface) @@ -331,6 +340,19 @@ def _create_lookup_choices(self, *args, **kwargs): ktc.annotations[template_record.SOURCE] = template_record.RECORDED return ktcs + @staticmethod + def can_fuse_vertical(scheduler, node1, node2, shared_data_score): + """Inductor's answer, but an npu int32 matmul's stored reader fuses into no node but a matmul: taken into + its own reader it would leave the matmul writing its int32 accumulator out.""" + return (not _int32_reader_apart(node1, node2) and + LookupTableChoices.can_fuse_vertical(scheduler, node1, node2, shared_data_score)) + + @staticmethod + def can_fuse_horizontal(scheduler, node1, node2, shared_data_score): + """Inductor's answer, but an npu int32 matmul's stored reader fuses into no node but a matmul.""" + return (not _int32_reader_apart(node1, node2) and + LookupTableChoices.can_fuse_horizontal(scheduler, node1, node2, shared_data_score)) + @staticmethod def should_use_persistent_reduction(features, cooperative_reduction): return generated_kernel_blocks.use_persistent_reduction( @@ -403,3 +425,194 @@ def _register_benchmarker(): from pytorchsim.backend import config_pick register_benchmarker("npu", config_pick.benchmark, override=True) + + +# Inductor's decompositions (torch._inductor.decomposition.decompositions): a patch, the table has no device hook + +def _register_decompositions(): + """npu's mm and bmm decomposed as with coordinate descent tuning off, which torchao's quantize_ turns on + for the process: a 1-row matmul stays one for postgrad/'s gemm rewrites, not a multiply and a sum.""" + from torch._inductor import decomposition + + packets = (torch.ops.aten.mm, torch.ops.aten.bmm) + for op, fn in list(decomposition.decompositions.items()): + if getattr(op, "overloadpacket", None) in packets and not getattr(fn, "_npu_without_cdt", False): + decomposition.decompositions[op] = _without_coordinate_descent(fn) + decomposition.fast_random_decomps.cache_clear() + + +def _without_coordinate_descent(fn): + """`fn`, traced with coordinate descent tuning off when its first operand is on npu.""" + from torch._inductor import config as inductor_config + + @functools.wraps(fn) + def decompose(self, *args, **kwargs): + if getattr(getattr(self, "device", None), "type", None) != "npu": + return fn(self, *args, **kwargs) + with inductor_config.patch(coordinate_descent_tuning=False): + return fn(self, *args, **kwargs) + + decompose._npu_without_cdt = True + return decompose + + +# Inductor's realize on reuse (ir.StorageBox.should_realize_on_reuse): a patch, it has no hook + +_NOT_ARITHMETIC = frozenset({"load", "load_seed", "to_dtype", "to_dtype_bitcast", "constant", "index_expr", + "indirect_indexing"}) + + +def _register_realize_on_broadcast(): + """A pointwise npu value of one element per row (last dimension 1) that a broadcast reads again is stored once + when it does more than load and cast, as XLA computes a row's scale in a fusion of its own; any other value, + and a bool, is computed where it is read, as before.""" + from torch._inductor import ir + from torch._inductor.virtualized import V + + original = ir.StorageBox.should_realize_on_reuse + if getattr(original, "_npu_broadcast", False): + return + + @functools.wraps(original) + def should_realize_on_reuse(self, users, *, graph_reuse=True): + if original(self, users, graph_reuse=graph_reuse): + return True + if graph_reuse or users <= 1 or not isinstance(self.data, ir.Pointwise) or not _is_npu_node(self.data): + return False + size = self.get_size() + return (len(size) > 0 and V.graph.sizevars.statically_known_equals(size[-1], 1) + and self.num_reads() > 0 and self.get_dtype() != torch.bool + and bool(set(self.data.inner_fn_opcount().used_ops) - _NOT_ARITHMETIC)) + + should_realize_on_reuse._npu_broadcast = True + ir.StorageBox.should_realize_on_reuse = should_realize_on_reuse + + +def _is_npu_node(node): + """Whether an IR node computes on npu.""" + from . import is_npu + return is_npu(node.get_device()) + + +# Inductor's node lowering (GraphLowering.run_node): a patch, it has no hook + +def _register_realize_dequant(): + """An int8 matmul's 16-bit dequantized npu result is stored, so it is the matmul's epilogue as XLA's convolution + fusion ends in bf16: inlined into its reader (a row norm, SiLU(gate) * up, the next quantization) it left the + matmul writing its int32 accumulator out and the reader reading it back.""" + from torch._inductor import ir + from torch._inductor.graph import GraphLowering + + original = GraphLowering.run_node + if getattr(original, "_npu_dequant", False): + return + + @functools.wraps(original) + def run_node(self, n): + result = original(self, n) + if isinstance(result, ir.TensorBox) and n in _dequant_ends(n.graph) and _is_npu_node(result): + result.realize() + return result + + run_node._npu_dequant = True + GraphLowering.run_node = run_node + + +_DEQUANT_ENDS = weakref.WeakKeyDictionary() + + +def _dequant_ends(graph): + """The FX nodes ending each aten._int_mm's dequantization: along its only users while they cast, view, or scale + or shift by a smaller operand, up to a cast back to float32, the first 16-bit float cast after the last scale.""" + if graph in _DEQUANT_ENDS: + return _DEQUANT_ENDS[graph] + aten, prims = torch.ops.aten, torch.ops.prims + casts = {prims.convert_element_type.default, aten._to_copy.default} + views = {aten.view.default, aten._unsafe_view.default, aten.reshape.default} + scales = {aten.mul.Tensor, aten.add.Tensor} + ends = set() + for mm in graph.find_nodes(op="call_function", target=aten._int_mm.default): + chain, node = [], mm + while len(node.users) == 1: + user = next(iter(node.users)) + if user.target in scales: + other = [a for a in user.args if a is not node] + if not other or (isinstance(other[0], torch.fx.Node) and _reach(other[0]) >= _reach(node)): + break + elif user.target not in casts | views: + break + if user.target in casts and _dtype(user) == torch.float32 and any(_dtype(c).itemsize == 2 for c in chain): + break + chain.append(user) + node = user + last = max((i for i, u in enumerate(chain) if u.target in scales), default=None) + if last is None: + continue + end = next((u for u in chain[last + 1:] if u.target in casts and _dtype(u) in (torch.bfloat16, torch.float16)), + chain[last] if _dtype(chain[last]) in (torch.bfloat16, torch.float16) else None) + if end is not None: + ends.add(end) + _DEQUANT_ENDS[graph] = ends + return ends + + +def _int32_reader_apart(node1, node2): + """Whether one of two scheduler nodes, neither a template, reads an npu template's int32 result.""" + if node1.is_template() or node2.is_template(): + return False + return _reads_int32_template(node1) or _reads_int32_template(node2) + + +def _reads_int32_template(node): + """Whether a scheduler node reads the int32 result of an npu matmul template.""" + from torch._inductor import ir + from torch._inductor.virtualized import V + for name in node.read_writes.buffer_names() - node.get_buffer_names(): + buf = V.graph.try_get_buffer(name) + if isinstance(buf, ir.TemplateBuffer) and buf.get_dtype() == torch.int32 and _is_npu_node(buf): + return True + return False + + +def _reach(node): + """The distinct elements an FX node's value holds (a broadcast dimension counted once), 0 when it records none.""" + val = node.meta.get("val") + if not isinstance(val, torch.Tensor): + return 0 + return functools.reduce(lambda a, b: a * b, (n for n, st in zip(val.shape, val.stride()) if st != 0), 1) + + +def _dtype(node): + """The dtype of an FX node's value, int8 when it records none.""" + val = node.meta.get("val") + return val.dtype if isinstance(val, torch.Tensor) else torch.int8 + + +# Inductor's template fusions (Scheduler._evaluate_pending_template_fusions): a patch, it has no hook + +def _register_template_fusion_futures(): + """Every pending template fusion is benchmarked: one whose compile future an earlier one already holds (two + templates whose fused kernels are one source, a W8A8 MLP's gate and up) is evaluated synchronously, since + Inductor maps each future to one pending fusion and dropped the other unbenchmarked.""" + from torch._inductor.scheduler import Scheduler + + original = Scheduler._evaluate_pending_template_fusions + if getattr(original, "_npu_futures", False): + return + + @functools.wraps(original) + def evaluate(self, candidates, fused_nodes): + taken = set() + for pending_fusions in candidates.values(): + for pending in pending_fusions: + future = pending.future.future if pending.future is not None else None + if future is None: + continue + if future in taken: + pending.future = None + else: + taken.add(future) + return original(self, candidates, fused_nodes) + + evaluate._npu_futures = True + Scheduler._evaluate_pending_template_fusions = evaluate diff --git a/scripts/ci/triton_route_passing.txt b/scripts/ci/triton_route_passing.txt index 8ae2f35c..9f6feb08 100644 --- a/scripts/ci/triton_route_passing.txt +++ b/scripts/ci/triton_route_passing.txt @@ -264,7 +264,10 @@ 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_int_mm.py tests/ops/gemm/test_row_matmul.py +tests/ops/gemm/test_w8a8_linear.py +tests/ops/gemm/test_widened_weight_mm.py tests/ops/gemm/test_zero_length_gemm.py tests/ops/misc/test_complex_to_real.py tests/ops/misc/test_custom_fused_kernel.py diff --git a/tests/ops/gemm/test_int_mm.py b/tests/ops/gemm/test_int_mm.py new file mode 100644 index 00000000..9b906e7d --- /dev/null +++ b/tests/ops/gemm/test_int_mm.py @@ -0,0 +1,102 @@ +"""An int8 matmul widened to int32 (torchao's W8A8 on a device out_dtype has no _int_mm for) on the npu, against +the CPU. Cases: int_mm, int_mm_weight_t (a Linear's [N, K] weight), int_mm_row (a 1 x K row), pass_graph (the mm +is aten._int_mm, counted), pass_graph_int16 (an int16 one stays an mm) and row_cdt (a row with coordinate descent +tuning on, as torchao's quantize_ sets it); run with [case ...], all when none is named.""" +import os +import sys + +import torch + +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), + "tests")) +from result_check import check_result + +device = torch.device("npu:0") + + +def _widened_mm(a, b): + return torch.mm(a.to(torch.int32), b.to(torch.int32)) + + +def _widened_mm_weight_t(a, w): + return torch.mm(a.to(torch.int32), w.t().to(torch.int32)) + + +#: name -> (fn, shapes) +CASES = { + "int_mm": (_widened_mm, [(64, 512), (512, 256)]), + "int_mm_weight_t": (_widened_mm_weight_t, [(64, 512), (256, 512)]), + "int_mm_row": (_widened_mm, [(1, 512), (512, 256)]), +} + + +def _inputs(shapes, dtype=torch.int8): + g = torch.Generator().manual_seed(0) + return [torch.randint(-128, 128, s, generator=g).to(dtype) for s in shapes] + + +def run_case(name): + fn, shapes = CASES[name] + args = _inputs(shapes) + ref = fn(*args) + torch._dynamo.reset() + out = torch.compile(fn, dynamic=False)(*[a.to(device) for a in args]) + check_result(f"IntMM {name}", out, ref) + return True + + +def _post_grad(fn, args): + from torch._inductor.decomposition import select_decomp_table + from torch.fx.experimental.proxy_tensor import make_fx + + from pytorchsim.frontend.inductor import postgrad as pg + gm = make_fx(fn, decomposition_table=select_decomp_table(), tracing_mode="fake")(*args) + pg.CALLS.clear() + pg.pytorchsim_post_grad_pass(gm) + targets = [n.target for n in gm.graph.nodes if n.op == "call_function"] + return targets, pg.CALLS.get("int_mm") + + +def run_pass_graph(name): + """On a traced graph: the widened int8 mm becomes aten._int_mm, counted.""" + targets, calls = _post_grad(_widened_mm_weight_t, _inputs([(64, 512), (256, 512)])) + ok = (torch.ops.aten._int_mm.default in targets and torch.ops.aten.mm.default not in targets + and calls == {"rewritten": 1}) + check_result("IntMM pass_graph", torch.tensor([ok]), torch.tensor([True])) + return ok + + +def run_pass_graph_int16(name): + """On a traced graph: an int16 mm widened to int32 is no _int_mm, and stays an mm.""" + targets, calls = _post_grad(_widened_mm, _inputs([(64, 512), (512, 256)], torch.int16)) + ok = (torch.ops.aten.mm.default in targets and torch.ops.aten._int_mm.default not in targets + and calls is None) + check_result("IntMM pass_graph_int16", torch.tensor([ok]), torch.tensor([True])) + return ok + + +def run_row_cdt(name): + """A 1 x K row compiled with coordinate descent tuning on, which would decompose the mm before the post-grad + pass: still int_mm's row on the npu, rewritten once, equal to the CPU.""" + from torch._inductor import config as inductor_config + + from pytorchsim.frontend.inductor import postgrad as pg + args = _inputs([(1, 512), (512, 256)]) + ref = _widened_mm(*args) + pg.CALLS.clear() + torch._dynamo.reset() + with inductor_config.patch(coordinate_descent_tuning=True): + out = torch.compile(_widened_mm, dynamic=False)(*[a.to(device) for a in args]) + ok = pg.CALLS.get("int_mm") == {"rewritten": 1} + check_result("IntMM row_cdt", out, ref) + check_result("IntMM row_cdt rewritten", torch.tensor([ok]), torch.tensor([True])) + return ok + + +EXTRA = {"pass_graph": run_pass_graph, "pass_graph_int16": run_pass_graph_int16, "row_cdt": run_row_cdt} + + +if __name__ == "__main__": + names = sys.argv[1:] or [*CASES, *EXTRA] + for n in names: + (EXTRA[n] if n in EXTRA else run_case)(n) diff --git a/tests/ops/gemm/test_w8a8_linear.py b/tests/ops/gemm/test_w8a8_linear.py new file mode 100644 index 00000000..a1610966 --- /dev/null +++ b/tests/ops/gemm/test_w8a8_linear.py @@ -0,0 +1,117 @@ +"""One Linear quantized W8A8 with torchao's quantize_ (int8 weights, int8 activations, int32 accumulation) on +the npu, against the same quantized Linear on the CPU. Cases: dynamic (a scale per activation row), static +(one calibrated activation scale) and rownorm (bf16, its output read by a row norm); [case ...], all when none. +Without torchao, W8A8Linear does the same math.""" +import os +import sys + +import torch +from torch import nn + +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), + "tests")) +from result_check import check_result + +device = torch.device("npu:0") +M, K, N = 64, 512, 256 + + +def _symmetric(t, scale): + """`t` divided by `scale`, rounded and clamped to int8.""" + return torch.round(t / scale).clamp(-128, 127).to(torch.int8) + + +class W8A8Linear(nn.Module): + """torchao's W8A8 Linear without torchao: an int8 weight with a scale per output channel, the input int8 per + row (act_scale None) or by act_scale, the int8 matmul in int32 as torchao emits it off cuda, then rescaled.""" + + def __init__(self, linear, act_scale=None): + super().__init__() + w = linear.weight.detach() + w_scale = w.abs().amax(1, keepdim=True).clamp(min=1e-8) / 127 + self.register_buffer("w_q", _symmetric(w, w_scale)) + self.register_buffer("w_scale", w_scale.reshape(1, -1)) + self.register_buffer("bias", None if linear.bias is None else linear.bias.detach().clone()) + self.register_buffer("act_scale", act_scale) + + def forward(self, x): + s = self.act_scale if self.act_scale is not None else x.abs().amax(-1, keepdim=True).clamp(min=1e-8) / 127 + acc = torch.mm(_symmetric(x, s).to(torch.int32), self.w_q.t().to(torch.int32)) + out = acc.to(torch.float32) * s * self.w_scale + return out if self.bias is None else out + self.bias + + +def _quantized(name, linear, x): + """`linear` quantized for case `name` (static calibrates its scale on `x`): torchao's, else W8A8Linear.""" + act_scale = (x.abs().amax() / 127).reshape(1, 1) if name == "static" else None + try: + from torchao.quantization import (Int8DynamicActivationInt8WeightConfig, + Int8StaticActivationInt8WeightConfig, quantize_) + from torchao.quantization.granularity import PerTensor + except ImportError: + return W8A8Linear(linear, act_scale), "W8A8Linear" + config = (Int8DynamicActivationInt8WeightConfig() if act_scale is None + else Int8StaticActivationInt8WeightConfig(act_quant_scale=act_scale, granularity=PerTensor())) + model = nn.Sequential(linear) + quantize_(model, config) + return model, "torchao" + + +def run_case(name): + torch.manual_seed(0) + linear, x = nn.Linear(K, N).eval(), torch.randn(M, K) + step = (x.abs().max() / 127 * linear.weight.detach().abs().max()).item() + with torch.no_grad(): + fp32 = linear(x) + model, by = _quantized(name, linear, x) + ref = model(x) + torch._dynamo.reset() + out = torch.compile(model.to(device), dynamic=False)(x.to(device)).cpu() + print(f"W8A8Linear {name} ({by}): max |npu - cpu int8| {(out - ref).abs().max().item():.3g}, " + f"max |cpu int8 - fp32| {(ref - fp32).abs().max().item():.3g}, one step {step:.3g}") + check_result(f"W8A8Linear {name}", out, ref, atol=step) + return True + + +def run_rownorm(name): + """A bf16 dynamic W8A8 Linear whose output a row RMS norm reads, as Qwen3's q_norm does: the npu result against + the CPU's, and its dequantized result stored by the int8 matmul's epilogue, so the wrapper holds no int32 buffer.""" + from torch._inductor.utils import run_and_get_code + + torch.manual_seed(0) + linear, x = nn.Linear(K, N, bias=False).to(torch.bfloat16).eval(), torch.randn(M, K, dtype=torch.bfloat16) + inner, by = _quantized("dynamic", linear, x) + if by != "torchao": + print(f"W8A8Linear {name}: skipped, it needs torchao's bf16 dequantization") + return True + model = _ThenRowNorm(inner) + with torch.no_grad(): + ref = model(x) + torch._dynamo.reset() + out, codes = run_and_get_code(torch.compile(model.to(device), dynamic=False), x.to(device)) + int32 = [l.strip() for c in codes for l in c.splitlines() if "empty_strided" in l and "torch.int32" in l] + print(f"W8A8Linear {name}: max |npu - cpu int8| {(out.cpu().float() - ref.float()).abs().max().item():.3g}, " + f"int32 buffers {int32}") + check_result(f"W8A8Linear {name}", out.cpu(), ref, rtol=5e-2, atol=5e-2) + check_result(f"W8A8Linear {name} (no int32 buffer)", torch.tensor([not int32]), torch.tensor([True])) + return True + + +class _ThenRowNorm(nn.Module): + """`inner`, then each output row divided by its root mean square taken in float32.""" + + def __init__(self, inner): + super().__init__() + self.inner = inner + + def forward(self, x): + y = self.inner(x) + return y * torch.rsqrt(y.float().pow(2).mean(-1, keepdim=True) + 1e-6).to(y.dtype) + + +CASES = ("dynamic", "static", "rownorm") + + +if __name__ == "__main__": + for n in sys.argv[1:] or CASES: + (run_rownorm if n == "rownorm" else run_case)(n) diff --git a/tests/ops/gemm/test_widened_weight_mm.py b/tests/ops/gemm/test_widened_weight_mm.py new file mode 100644 index 00000000..072d50e7 --- /dev/null +++ b/tests/ops/gemm/test_widened_weight_mm.py @@ -0,0 +1,77 @@ +"""A weight-only int8 matmul (W8A16: an int8 weight widened to bf16, then a bf16 mm) on the npu, against the +same math in float32 on the CPU. Cases: weight_t (a Linear's [N, K] weight, transposed, as torchao's), weight_kn +(stored [K, N]), row (a 1 x K input) and pass_compiled (compiled, the transposed widening is stored row-major, +counted once; the row-major one is left); run with [case ...], all when none is named.""" +import os +import sys + +import torch + +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), + "tests")) +from result_check import check_result + +device = torch.device("npu:0") + + +def _weight_t(x, w): + return torch.mm(x, w.t().to(torch.bfloat16)) + + +def _weight_kn(x, w): + return torch.mm(x, w.to(torch.bfloat16)) + + +#: name -> (fn, x shape, w shape, whether w is stored [N, K]) +CASES = { + "weight_t": (_weight_t, (64, 512), (256, 512), True), + "weight_kn": (_weight_kn, (64, 512), (512, 256), False), + "row": (_weight_t, (1, 512), (256, 512), True), +} + + +def _inputs(x_shape, w_shape): + g = torch.Generator().manual_seed(0) + x = torch.randn(x_shape, generator=g).to(torch.bfloat16) + w = torch.randint(-128, 128, w_shape, generator=g).to(torch.int8) + return x, w + + +def run_case(name): + """Compile the case on the npu; the reference is the same widened weight and input in float32.""" + fn, xs, ws, nk = CASES[name] + x, w = _inputs(xs, ws) + ref = torch.mm(x.float(), w.float().t() if nk else w.float()).to(torch.bfloat16).float() + torch._dynamo.reset() + out = torch.compile(fn, dynamic=False)(x.to(device), w.to(device)).cpu().float() + check_result(f"WidenedWeightMM {name}", out, ref, rtol=1e-2, atol=ref.abs().max().item() * 1e-2) + return True + + +def run_pass_compiled(name): + """Compiled on the npu with Inductor's caches off (so the pass runs): the transposed widening is stored + row-major by mm_widened_weight, once; the row-major one is left alone.""" + from torch._inductor import config as inductor_config + + from pytorchsim.frontend.inductor import postgrad as pg + counts = [] + for fn, xs, ws, _ in (CASES["weight_t"], CASES["weight_kn"]): + x, w = _inputs(xs, ws) + pg.CALLS.clear() + torch._dynamo.reset() + with inductor_config.patch(force_disable_caches=True): + torch.compile(fn, dynamic=False)(x.to(device), w.to(device)) + counts.append(pg.CALLS.get("mm_widened_weight")) + ok = counts == [{"rewritten": 1}, None] + print("mm_widened_weight counts (weight_t, weight_kn):", counts) + check_result("WidenedWeightMM pass_compiled", torch.tensor([ok]), torch.tensor([True])) + return ok + + +EXTRA = {"pass_compiled": run_pass_compiled} + + +if __name__ == "__main__": + names = sys.argv[1:] or [*CASES, *EXTRA] + for n in names: + (EXTRA[n] if n in EXTRA else run_case)(n) diff --git a/tests/system/stub_compile.py b/tests/system/stub_compile.py index 18d299ff..df433a63 100644 --- a/tests/system/stub_compile.py +++ b/tests/system/stub_compile.py @@ -1,9 +1,15 @@ """A graph lowered with its Triton kernels not compiled: what a test of the lowering's decisions reads.""" +import concurrent.futures import contextlib from unittest import mock class _NotCompiled: + def __init__(self): + """A kernel that launches nothing, its precompile already done (Inductor's (_, elapsed_us) result).""" + self.future = concurrent.futures.Future() + self.future.set_result((None, 0)) + def run(self, *args, **kwargs): return None @@ -12,5 +18,5 @@ def run(self, *args, **kwargs): def kernels_not_compiled(): """Inductor's async_compile.triton hands back a kernel that launches nothing, so no kernel reaches PTB.""" from torch._inductor.async_compile import AsyncCompile - with mock.patch.object(AsyncCompile, "triton", lambda self, name, source, device_str="cuda": _NotCompiled()): + with mock.patch.object(AsyncCompile, "triton", lambda self, *args, **kwargs: _NotCompiled()): yield diff --git a/tests/system/test_on_chip.py b/tests/system/test_on_chip.py new file mode 100644 index 00000000..f758a353 --- /dev/null +++ b/tests/system/test_on_chip.py @@ -0,0 +1,90 @@ +"""A graph's intermediates kept in the scratchpad (autotune/on_chip.py): a tensor a kernel makes, every use of +which is a matmul operand, kept where it fits beside the others; its maker and its readers state it by tensor +index, and a kept and a moved build of one source do not share a Triton cache key.""" +import json +import os +import sys + +sys.path.insert(0, os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim")) +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), "tests", "system")) + +import torch # noqa: E402 the npu backend loads pytorchsim whole, before its parts are imported +from pytorchsim.backend import compiler_input # noqa: E402 +from pytorchsim.frontend.inductor.autotune import on_chip # noqa: E402 +from test_graph_prefetch import _Graph, _compiled_metas # noqa: E402 + +_A = torch.ops.aten + + +def _kept(g): + """The names of the nodes `g` keeps on chip.""" + return sorted(n.name for n in on_chip.elected(g)) + + +def test_a_matmul_operand_a_kernel_makes_is_kept(): + """Breaks if an int8 activation an _int_mm alone reads, through a view, is not kept, or its input is.""" + g = _Graph() + x, w = g.input("x", 1024, 1024), g.input("w", 1024, 1024) + q = g.op(_A.mul.Tensor, x, x) + y = g.op(_A.mm.default, g.op(_A.view.default, q, [1024, 1024]), w) + g.graph.output(y) + assert _kept(g) == [q.name], _kept(g) + + +def test_an_elementwise_co_use_is_not_kept(): + """Breaks if an intermediate an elementwise op reads beside a matmul is kept.""" + g = _Graph() + x, w = g.input("x", 1024, 1024), g.input("w", 1024, 1024) + q = g.op(_A.mul.Tensor, x, x) + g.graph.output((g.op(_A.mm.default, q, w), g.op(_A.add.Tensor, q, x))) + assert _kept(g) == [], _kept(g) + + +def test_a_returned_intermediate_is_not_kept(): + """Breaks if an intermediate the graph returns is kept: it has to reach DRAM.""" + g = _Graph() + x, w = g.input("x", 1024, 1024), g.input("w", 1024, 1024) + q = g.op(_A.mul.Tensor, x, x) + g.graph.output((g.op(_A.mm.default, q, w), q)) + assert _kept(g) == [], _kept(g) + + +def test_an_intermediate_over_the_budget_is_not_kept(): + """Breaks if an intermediate larger than the resident budget a lane is kept.""" + g = _Graph() + x, w = g.input("x", 8192, 16384), g.input("w", 16384, 128) + q = g.op(_A.mul.Tensor, x, x) + g.graph.output(g.op(_A.mm.default, q, w)) + assert _kept(g) == [], _kept(g) + + +def test_the_spec_and_the_compile_key_hold_the_statement(): + """Breaks if on_chip's names are not the tensor indices of the JSON spec, or a kept and a moved build of one + source share a Triton cache key: the spec rides the compile's options, which the key hashes.""" + from triton.backends.pytorchsim.compiler import CPUOptions + args = [{"name": n, "role": r} for n, r in (("arg_A", "in"), ("arg_B", "in"), ("out_ptr0", "out"))] + meta = {"kernel_name": "mm", "args": args, "graph_prefetch": [], "on_chip": ["arg_A", "out_ptr0"], + "signature": {}, "constants": {}} + assert compiler_input.on_chip(meta) == (0, 2) + spec = lambda chip: json.dumps(compiler_input.spec_dict( # noqa: E731 + [("in", 64), ("in", 64), ("out", 64)], (1, 1, 1), on_chip=chip)) + assert json.loads(spec((0, 2)))["on_chip"] == [0, 2] and "on_chip" not in json.loads(spec(())) + assert CPUOptions(pytorchsim_spec=spec((0, 2))).hash() != CPUOptions(pytorchsim_spec=spec(())).hash() + + +def test_a_compiled_chain_states_the_kept_activation_at_both_ends(): + """Breaks if relu(x @ w1), which only the second mm reads, is not stated on chip by the kernel making it + and by the mm reading it, or a graph input or the returned output is.""" + g = torch.Generator().manual_seed(0) + x, w1, w2 = (torch.randn(*s, generator=g).to(torch.bfloat16) + for s in ((256, 1024), (1024, 1024), (1024, 2048))) + got = _compiled_metas(lambda x, w1, w2: torch.relu(x @ w1) @ w2, x, w1, w2) + roles = sorted(tuple(a["role"] for a in m["args"] if a["name"] in m["on_chip"]) for m in got) + assert roles == [("in",), ("out",)], [(m["kernel_name"], m["on_chip"]) for m in got] + + +if __name__ == "__main__": + for name, fn in list(globals().items()): + if name.startswith("test_"): + fn() + print(f"PASS {name}") diff --git a/third_party/pytorchsim-triton-backend.json b/third_party/pytorchsim-triton-backend.json index 6731fa83..98a3f1f3 100644 --- a/third_party/pytorchsim-triton-backend.json +++ b/third_party/pytorchsim-triton-backend.json @@ -2,6 +2,6 @@ "description": "Pin for the compiler the codegen route lowers through: PyTorchSim-Triton-Backend, with its LLVM, Triton, the Coprocessor environment (RISC-V toolchain, pk, Spike, gem5), the accelerator model, and TOGSim, which the compiler carries as its third_party/TOGSim submodule: this pin is therefore also what pins the Simulator, the runtime header and the machine configs. CI builds its base image FROM ghcr.io/psal-postech/pytorchsim-triton-backend:, the image that repository publishes for every commit on its main and develop, so ref must be such a commit. scripts/build_from_source.sh checks the same ref out for a local toolchain. The repository is private; its package grants this repository read access.", "pytorchsim_triton_backend": { "repository": "PSAL-POSTECH/PyTorchSim-Triton-Backend", - "ref": "f289fb35f1ce4d0be03834acfe90d70de502f7e1" + "ref": "7e1c3686424eb09fae94c97260ef25faf7a33da6" } }