Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
13 commits
Select commit Hold shift + click to select a range
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
68 changes: 32 additions & 36 deletions device/csrc/aten/native/Extra.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#include "Extra.h"

#include <ATen/Dispatch.h>
#include <ATen/OpMathType.h>
#include <ATen/core/grad_mode.h>

namespace at::native::openreg {
Expand Down Expand Up @@ -124,15 +126,12 @@ at::Tensor custom_autograd_fn_aliasing(at::Tensor x) {
capabilities are fully supported.

Current Limitations:
- dtype: Float only
- input tensor: must be contiguous layout
- dtype: integral, Float, Double, Half and BFloat16 (no Bool or complex)
- a non-contiguous iteration runs on a contiguous copy of the input
*/
// LITERALINCLUDE START: STUB ABS
void abs_kernel(at::TensorIteratorBase& iter) {
TORCH_CHECK(iter.ntensors() == 2, "Abs kernel expects 2 tensors");
TORCH_CHECK(
iter.common_dtype() == at::ScalarType::Float,
"Abs kernel only supports float type");

auto& output_tensor = iter.tensor(0);
auto& input_tensor = iter.tensor(1);
Expand All @@ -141,37 +140,34 @@ void abs_kernel(at::TensorIteratorBase& iter) {
input_tensor.sizes() == output_tensor.sizes(),
"Input and output tensor sizes must match.");

auto abs_loop = [](float* out_ptr, const float* in_ptr, int64_t n) {
for (int64_t i = 0; i < n; ++i) {
out_ptr[i] = std::abs(in_ptr[i]);
}
};

MemoryGuard guard(input_tensor, output_tensor);

if (iter.is_contiguous()) {
abs_loop(
static_cast<float*>(iter.data_ptr(0)),
static_cast<float*>(iter.data_ptr(1)),
iter.numel());
} else {
TORCH_CHECK(
input_tensor.is_contiguous(), "Input tensor must be contiguous.")

auto output = at::empty(
input_tensor.sizes(),
input_tensor.options().memory_format(
input_tensor.suggest_memory_format()));

MemoryGuard guard(output);

abs_loop(
static_cast<float*>(output.data_ptr()),
static_cast<float*>(iter.data_ptr(1)),
iter.numel());

output_tensor.copy_(output);
}
AT_DISPATCH_ALL_TYPES_AND2(
at::kHalf, at::kBFloat16, iter.common_dtype(), "abs_kernel", [&]() {
auto abs_loop = [](scalar_t* out_ptr, const scalar_t* in_ptr, int64_t n) {
for (int64_t i = 0; i < n; ++i) {
out_ptr[i] = static_cast<scalar_t>(
std::abs(static_cast<at::opmath_type<scalar_t>>(in_ptr[i])));
}
};

if (iter.is_contiguous()) {
MemoryGuard guard(input_tensor, output_tensor);
abs_loop(
static_cast<scalar_t*>(iter.data_ptr(0)),
static_cast<const scalar_t*>(iter.data_ptr(1)),
iter.numel());
} else {
auto input = input_tensor.contiguous();
auto output = at::empty(input.sizes(), input.options());
{
MemoryGuard guard(input, output);
abs_loop(
static_cast<scalar_t*>(output.data_ptr()),
static_cast<const scalar_t*>(input.const_data_ptr()),
input.numel());
}
output_tensor.copy_(output);
}
});
}
// LITERALINCLUDE END: STUB ABS

Expand Down
5 changes: 5 additions & 0 deletions device/csrc/runtime/OpenRegGuard.h
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,11 @@ struct OpenRegGuardImpl final : public c10::impl::DeviceGuardImplInterface {
*/
void synchronizeEvent(void* event) const override {}

/**
* Wait until all work on the device is done; the device runs synchronously.
*/
void synchronizeDevice(const c10::DeviceIndex device_index) const override {}

/**
* Ensure the caching allocator (if any) is aware that the given DataPtr is
* being used on the given stream, and that it should thus avoid recycling the
Expand Down
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
Loading
Loading