Skip to content
Merged
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
171 changes: 0 additions & 171 deletions pytorchsim/backend/codecache.py

This file was deleted.

7 changes: 4 additions & 3 deletions pytorchsim/backend/compiler_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,8 @@ def compiler_env():

def run_pipeline(spec_path, workdir, to_stage="pytorchsim-compile", tog=False, timeout=None):
"""Drive the compiler's stages over `spec_path`, writing artifacts into `workdir`, up to
`to_stage` (by default `pytorchsim-compile`, the ELF). `timeout` is seconds, by default
`to_stage` (by default `pytorchsim-compile`, the ELF); a run that leaves failure.json stopped, even when
it exits 0 because the kernel file declares that stop. `timeout` is seconds, by default
TORCHSIM_COMPILE_TIMEOUT or 1800; 0 waits as long as it takes."""
if timeout is None:
timeout = int(os.environ.get("TORCHSIM_COMPILE_TIMEOUT") or 1800)
Expand All @@ -147,8 +148,8 @@ def run_pipeline(spec_path, workdir, to_stage="pytorchsim-compile", tog=False, t

proc = subprocess.run(cmd, capture_output=True, text=True,
cwd=compiler_dir(), env=compiler_env(), timeout=timeout)
if proc.returncode != 0:
failure = compiler_contract("failure").read(workdir)
failure = compiler_contract("failure").read(workdir)
if proc.returncode != 0 or failure:
said = (f"at {failure['stage']} ({failure['kind']}): {failure['message']}" if failure
else f"outside every stage:\n{proc.stderr}")
raise CompilerError(f"the compiler pipeline failed (exit {proc.returncode}) {said}",
Expand Down
36 changes: 36 additions & 0 deletions pytorchsim/backend/compiler_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,42 @@ def write(src_code, meta, path, recorded=None, scalars=None):
return path


def spec_json(meta):
"""The kernel's spec in the compiler's JSON_FIELDS form (contract/kernel_spec), as the PTB Triton backend
takes it in the pytorchsim_spec option: what its Triton IR does not hold. The kernel's name, signature
and each tensor's name and dtype are the IR's; each tensor is stated by role and storage span, in order."""
missing = [a["name"] for a in meta["args"] if not a["numel"]]
if missing:
raise SpecIncomplete(f"{meta['kernel_name']}: no numel for {missing} -- "
f"collect_meta could not resolve them from V.graph")
scalars = scalar_args(meta)
return json.dumps(spec_dict(
[(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}}))


def backend_options(spec):
"""The Triton backend's options for a kernel whose spec JSON is `spec`: the spec, whether the compile builds the
TOG (timing mode), and the machine TORCHSIM_TARGET names, which the compile otherwise takes from its environment."""
from pytorchsim import config
return {"pytorchsim_spec": spec, "pytorchsim_tog": bool(config.pytorchsim_timing_mode),
"pytorchsim_target": compiler_bridge.target().file}


_UNSIGNED = {"uint8": "uint8", "uint16": "uint16", "uint32": "uint32", "uint64": "uint64"}
"""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):
"""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."""
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 {}}


META_JSON = "meta.json"


Expand Down
44 changes: 44 additions & 0 deletions pytorchsim/backend/config_pick.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""Which of a kernel's compiled configs runs: Inductor's autotuner times each through the benchmarker registered
for npu. Functional mode picks the first that compiled, in the order its candidates were offered, without
launching any; timing mode launches each as a measurement, which TOGSim answers in cycles."""

import contextlib
import itertools
import threading

from pytorchsim.backend import template_record

_ORDER = itertools.count(1)
_STATE = threading.local()


def measuring():
"""Whether a launch is being timed by the benchmarker: it then yields its cycles and runs nothing else."""
return getattr(_STATE, "cycles", None) is not None


def report(cycles):
"""The launch being measured took `cycles` on TOGSim."""
_STATE.cycles.append(cycles)


def benchmark(benchmarker, fn, *, warmup, rep, **kwargs):
"""The 'time' of fn, in ms: in functional mode later calls are larger, so the first config offered wins
and fn is not called; in timing mode fn launches the kernel, and TOGSim's cycles (1 cycle = 1 ns) come back,
inf when it launched nothing (an extern kernel) or did not simulate."""
from pytorchsim import config
if not config.pytorchsim_timing_mode:
template_record.warn_untimed_autotune()
return next(_ORDER) * 1e-3
with _measure() as got:
fn()
return got[-1] * 1e-6 if got else float("inf")


@contextlib.contextmanager
def _measure():
_STATE.cycles = []
try:
yield _STATE.cycles
finally:
_STATE.cycles = None
25 changes: 25 additions & 0 deletions pytorchsim/backend/launch_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,28 @@
launch's inputs, and at every call Inductor leaves to aten (the generated wrapper's torchsim_extern)."""

_LAUNCH_OBSERVERS = {}
_USER_KERNEL_NAMES = {}
_EVERY_LAUNCH = []
_EVERY_LAUNCH_INPUTS = []
_EVERY_EXTERN = []
_CALL_NAMES = []


def user_kernel_id(kernel):
"""A user-defined Triton kernel's name in its launch meta: its module and qualified name."""
return f"{kernel.__module__}.{kernel.__qualname__}"


def user_kernel_of(kernel_name):
"""The id of the user-defined Triton kernel that compiled as `kernel_name`, or None."""
return _USER_KERNEL_NAMES.get(kernel_name)


def name_user_kernel(kernel_name, kernel):
"""Record that `kernel_name` is the compile of the user-defined Triton kernel `kernel`."""
_USER_KERNEL_NAMES[kernel_name] = user_kernel_id(kernel)


def observe_launches(kernel, callback):
"""Call `callback()` at every launch of the user-defined Triton kernel `kernel`."""
_LAUNCH_OBSERVERS[user_kernel_id(kernel)] = callback
Expand Down Expand Up @@ -40,6 +52,19 @@ def torchsim_extern(call):
callback(call)


def torchsim_call(names):
"""The generated wrapper's note before a Triton kernel's call: the buffer each argument is, taken by the
launch that follows it (a kernel's variable in the wrapper is not the name its binary carries)."""
_CALL_NAMES[:] = [names]


def take_call_names(count):
"""The buffer names of the first `count` arguments the wrapper noted for this launch, once (a template's
call also lists its grid), or None when it noted none (a launch made while Inductor benchmarks)."""
names = _CALL_NAMES.pop() if _CALL_NAMES else None
return names[:count] if names is not None and len(names) >= count else None


def notify_launch(launcher, args):
"""Call, before `launcher` runs: its user-defined kernel's observer, every launch's, and every
launch's with its inputs."""
Expand Down
Loading
Loading