Skip to content
Open
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
10 changes: 7 additions & 3 deletions .github/workflows/pytorchsim_test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docker/Dockerfile.base
Original file line number Diff line number Diff line change
Expand Up @@ -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 \
Expand Down
21 changes: 17 additions & 4 deletions pytorchsim/backend/compiler_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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},
)
Expand All @@ -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):
Expand All @@ -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<i8>)."""


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"
Expand Down
2 changes: 1 addition & 1 deletion pytorchsim/contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
1 change: 1 addition & 0 deletions pytorchsim/frontend/inductor/autotune/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
"""


Expand Down
13 changes: 11 additions & 2 deletions pytorchsim/frontend/inductor/autotune/graph_prefetch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
25 changes: 23 additions & 2 deletions pytorchsim/frontend/inductor/autotune/mm_resident.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,19 +94,40 @@ 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
why, got = decline(kernel_inputs)
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."""
Expand Down
78 changes: 78 additions & 0 deletions pytorchsim/frontend/inductor/autotune/on_chip.py
Original file line number Diff line number Diff line change
@@ -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
7 changes: 5 additions & 2 deletions pytorchsim/frontend/inductor/codegen/kernel_metadata.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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))

Expand Down Expand Up @@ -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": [],
}


Expand Down Expand Up @@ -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": [],
}


Expand Down
3 changes: 2 additions & 1 deletion pytorchsim/frontend/inductor/codegen/scheduling.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down
3 changes: 2 additions & 1 deletion pytorchsim/frontend/inductor/codegen/user_kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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),
}
3 changes: 3 additions & 0 deletions pytorchsim/frontend/inductor/postgrad/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading