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
2 changes: 2 additions & 0 deletions .github/workflows/pytorchsim_test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ jobs:
- tests/system/test_route_allowlist.py
- tests/system/test_select.py
- tests/system/test_session_cycles.py
- tests/system/test_spike_placement.py
- tests/system/test_tensor_placement.py
- tests/system/test_togsim_exit.py
- tests/system/test_togsim_result.py
- tests/system/test_verify_golden.py
Expand Down
81 changes: 80 additions & 1 deletion device/third_party/openreg/csrc/memory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

#include <include/openreg.h>

#include <cstdint>
#include <iterator>
#include <map>
#include <mutex>

Expand All @@ -13,6 +15,56 @@ struct Block {
void* pointer = nullptr;
size_t size = 0;
int refcount{0};
uint64_t sim_addr = 0;
uint64_t sim_size = 0;
};

// The simulated DRAM device blocks are allocated in: 16 KiB-aligned ranges from 0, first fit over the holes that
// freed blocks left, else above everything allocated; a freed range coalesces with its neighbours.
class SimDram {
public:
static constexpr uint64_t kAlign = 16 * 1024;

uint64_t allocate(uint64_t bytes) {
const uint64_t need = (bytes + kAlign - 1) / kAlign * kAlign;
for (auto it = m_holes.begin(); it != m_holes.end(); ++it) {
if (it->second < need)
continue;
const uint64_t at = it->first, left = it->second - need;
m_holes.erase(it);
if (left)
m_holes[at + need] = left;
return at;
}
const uint64_t at = m_top;
m_top += need;
return at;
}

void free(uint64_t at, uint64_t bytes) {
uint64_t start = at, len = (bytes + kAlign - 1) / kAlign * kAlign;
auto next = m_holes.lower_bound(start);
if (next != m_holes.end() && start + len == next->first) {
len += next->second;
next = m_holes.erase(next);
}
if (next != m_holes.begin()) {
auto prev = std::prev(next);
if (prev->first + prev->second == start) {
start = prev->first;
len += prev->second;
m_holes.erase(prev);
}
}
if (start + len == m_top)
m_top = start;
else
m_holes[start] = len;
}

private:
std::map<uint64_t, uint64_t> m_holes;
uint64_t m_top = 0;
};

class MemoryManager {
Expand Down Expand Up @@ -48,7 +100,12 @@ class MemoryManager {
}
}

m_registry[mem] = {type, current_device, mem, aligned_size, 0};
Block block{type, current_device, mem, aligned_size, 0};
if (type == orMemoryType::orMemoryTypeDevice) {
block.sim_size = size;
block.sim_addr = m_sim_dram.allocate(size);
}
m_registry[mem] = block;
*ptr = mem;
return orSuccess;
}
Expand All @@ -64,6 +121,7 @@ class MemoryManager {

const auto& info = it->second;
if (info.type == orMemoryType::orMemoryTypeDevice) {
m_sim_dram.free(info.sim_addr, info.sim_size);
openreg::mprotect(info.pointer, info.size, F_PROT_READ | F_PROT_WRITE);
openreg::munmap(info.pointer, info.size);
} else {
Expand Down Expand Up @@ -140,6 +198,18 @@ class MemoryManager {
return orSuccess;
}

orError_t getSimAddress(uint64_t* addr, const void* ptr) {
if (!addr || !ptr)
return orErrorUnknown;
std::lock_guard<std::mutex> lock(m_mutex);
Block* info = getBlockInfoNoLock(ptr);
if (!info || info->type != orMemoryType::orMemoryTypeDevice)
return orErrorUnknown;
*addr = info->sim_addr + static_cast<uint64_t>(static_cast<const char*>(ptr) -
static_cast<const char*>(info->pointer));
return orSuccess;
}

orError_t unprotect(void* ptr) {
std::lock_guard<std::mutex> lock(m_mutex);
return unprotectNoLock(getBlockInfoNoLock(ptr));
Expand Down Expand Up @@ -197,6 +267,7 @@ class MemoryManager {
}

std::map<void*, Block> m_registry;
SimDram m_sim_dram;
std::mutex m_mutex;
};

Expand Down Expand Up @@ -250,6 +321,14 @@ orError_t orPointerGetAttributes(
return MemoryManager::getInstance().getPointerAttributes(attributes, ptr);
}

orError_t orPointerGetSimAddress(uint64_t* simAddr, const void* devPtr) {
return MemoryManager::getInstance().getSimAddress(simAddr, devPtr);
}

size_t orSimAddressAlignment(void) {
return SimDram::kAlign;
}

orError_t orMemoryUnprotect(void* devPtr) {
return MemoryManager::getInstance().unprotect(devPtr);
}
Expand Down
5 changes: 5 additions & 0 deletions device/third_party/openreg/include/openreg.h
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#pragma once

#include <cstddef>
#include <cstdint>

#ifdef _WIN32
#define OPENREG_EXPORT __declspec(dllexport)
Expand Down Expand Up @@ -62,6 +63,10 @@ OPENREG_EXPORT orError_t orMemcpyAsync(
orStream_t stream);
OPENREG_EXPORT orError_t
orPointerGetAttributes(orPointerAttributes* attributes, const void* ptr);
// The simulated DRAM address of a device pointer: its block's 16 KiB-aligned range, given at orMalloc and
// returned at orFree, plus the pointer's offset in it. orErrorUnknown for a pointer of no device block.
OPENREG_EXPORT orError_t orPointerGetSimAddress(uint64_t* simAddr, const void* devPtr);
OPENREG_EXPORT size_t orSimAddressAlignment(void);
OPENREG_EXPORT orError_t orMemoryUnprotect(void* devPtr);
OPENREG_EXPORT orError_t orMemoryProtect(void* devPtr);

Expand Down
20 changes: 20 additions & 0 deletions device/torch_openreg/csrc/Module.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,24 @@ PyObject* _addTaskToStream(PyObject* self, PyObject* args) {
END_HANDLE_TH_ERRORS
}

// The simulated DRAM address of the device pointer `arg` (an int): orPointerGetSimAddress's.
PyObject* _simAddress(PyObject* self, PyObject* arg) {
HANDLE_TH_ERRORS
TORCH_CHECK(THPUtils_checkLong(arg), "_sim_address expects an int pointer");
const void* ptr = reinterpret_cast<const void*>(THPUtils_unpackUInt64(arg));
uint64_t addr = 0;
TORCH_CHECK(orPointerGetSimAddress(&addr, ptr) == orSuccess, "pointer ", ptr,
" is in no npu storage, so it has no simulated DRAM address");
return THPUtils_packUInt64(addr);
END_HANDLE_TH_ERRORS
}

PyObject* _simAddressAlignment(PyObject* self, PyObject* noargs) {
HANDLE_TH_ERRORS
return THPUtils_packUInt64(orSimAddressAlignment());
END_HANDLE_TH_ERRORS
}

static PyMethodDef methods[] = {
{"_init", _initExtension, METH_NOARGS, nullptr},
{"_get_default_generator", _getDefaultGenerator, METH_O, nullptr},
Expand All @@ -261,6 +279,8 @@ static PyMethodDef methods[] = {
{"_device_synchronize", _deviceSynchronize, METH_NOARGS, nullptr},
// Stream task functions
{"_add_task_to_stream", _addTaskToStream, METH_VARARGS, nullptr},
{"_sim_address", _simAddress, METH_O, nullptr},
{"_sim_address_alignment", _simAddressAlignment, METH_NOARGS, nullptr},
{nullptr, nullptr, 0, nullptr}};

/*
Expand Down
15 changes: 15 additions & 0 deletions device/torch_openreg/openreg/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,19 @@ def sync_task():

torch_openreg._C._device_synchronize()

def sim_address(tensor):
"""The simulated DRAM address of `tensor`'s first element: its storage's range, given when the storage was
allocated and returned when it is freed, plus the tensor's byte offset in it. TOGSim places it there."""
if tensor.device.type != "npu":
raise ValueError(f"sim_address: a {tensor.device} tensor has no simulated DRAM address, only an npu one")
return torch_openreg._C._sim_address(tensor.data_ptr())


def sim_address_alignment():
"""Alignment in bytes of every storage's simulated DRAM range; a view's address may be less aligned."""
return torch_openreg._C._sim_address_alignment()


def get_tog_simulator():
return _tog_simulator

Expand Down Expand Up @@ -352,6 +365,8 @@ def register_eager_to_compile(ops):
"launch_kernel",
"launch_model",
"synchronize",
"sim_address",
"sim_address_alignment",
"get_tog_simulator",
"set_tog_simulator",
"TOGSimulator",
Expand Down
2 changes: 1 addition & 1 deletion pytorchsim/backend/build_identity.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
STAMP_NAME = "provenance.json"


_STALE_PATTERNS = ("[0-9][0-9]-*", "tog.so", "tog_cycles.tsv", "tog_units.tsv", "timing.json", "copy_node_*/tog.*")
_STALE_PATTERNS = ("[0-9][0-9]-*", "tog.so", "tog_tile_cycles.tsv", "tog_unit_table.tsv", "timing.json", "copy_node_*/tog.*")


_identity = None
Expand Down
44 changes: 9 additions & 35 deletions pytorchsim/simulator/functional/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,13 @@
from pytorchsim.backend import compiler_bridge
from pytorchsim.contract import storage_span
from pytorchsim.simulator.functional import spike
from pytorchsim.simulator.placement import ShapeMismatch, tensor_args, write_tensor_addrs # noqa: F401

logger = config.setup_logger()

REPLAY_DIR = ".triton_replay"


class ShapeMismatch(RuntimeError):
"""The launch does not match the shapes the binary was compiled for."""


def run(workdir, meta, args):
"""Execute the kernel on the launch's tensors. Returns the names written. Takes no lock: every
file it writes is in this process's runtime_dir. Replay is off by default."""
Expand Down Expand Up @@ -49,15 +46,16 @@ def run(workdir, meta, args):


def write_inputs(workdir, meta, args):
"""Write every arg as runtime/<name>.raw. Returns the runtime directory. Inputs are scattered
to the addresses the kernel computes; outputs are zeros, since the wrapper dumps by argv position."""
"""Write every arg as runtime/<name>.raw, and placement's tensor addresses beside them. Returns
the runtime directory. Inputs are scattered to the addresses the kernel computes; outputs are zeros."""
import numpy as np
import torch

pairs = tensor_args(meta, args)
_check(meta, pairs)

runtime = contract.runtime_dir(workdir)
write_tensor_addrs(workdir, meta, args)
for m, t in pairs:
path = os.path.join(runtime, f"{m['name']}.raw")
if m["role"] not in ("in", "inout"):
Expand All @@ -68,21 +66,11 @@ def write_inputs(workdir, meta, args):


def flat_input(m, t):
"""The launch tensor `t` of arg `m` as the kernel sees it: a CPU tensor of m's numel elements, each
at the address `t`'s strides put it, what its .raw file holds."""
import torch

cpu = t.detach().to("cpu")
flat = torch.zeros(m["numel"], dtype=cpu.dtype, device="cpu")
shape, strides = list(t.shape), list(t.stride())
src = cpu
for i in range(len(strides) - 1, -1, -1):
if strides[i] == 0:
src = src.select(i, 0)
shape.pop(i)
strides.pop(i)
flat.as_strided(shape, strides).copy_(src)
return flat
"""The launch tensor `t` of arg `m` as the kernel sees it: m's numel elements of t's storage from t's offset,
what its .raw file holds -- the storage's own bytes between t's elements, so args that are views of one
storage, placed overlapping, agree wherever the wrapper copies their .raw files over each other."""
span = t.detach().as_strided((m["numel"],), (1,), t.storage_offset())
return span.to("cpu").clone()


def read_outputs(workdir, meta, args):
Expand Down Expand Up @@ -110,20 +98,6 @@ def read_outputs(workdir, meta, args):
return written


def tensor_args(meta, args):
"""[(arg_meta, tensor)] for the launch, paired by position: Inductor passes the tensors first,
in signature order, so meta["args"] lines up with the leading arguments."""
import torch

tensors = [a for a in args if isinstance(a, torch.Tensor)]
metas = meta["args"]
if len(tensors) != len(metas):
raise ShapeMismatch(
f"{meta['kernel_name']}: launch passed {len(tensors)} tensor(s), "
f"but the spec declares {len(metas)} ({[m['name'] for m in metas]})")
return list(zip(metas, tensors))


def _check(meta, pairs):
for m, t in pairs:
if _storage_numel(t) != m["numel"]:
Expand Down
74 changes: 74 additions & 0 deletions pytorchsim/simulator/placement.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
"""Where a launch's tensors sit in simulated DRAM, the one file Spike and TOGSim both read: per kernel argument in
order, the address the device allocator gave its storage plus its offset (the compiler's TENSOR_ADDRS_FILE).
Spike's copy goes beside the .raw files in runtime/, TOGSim's into the launch directory beside tog.so."""

import os

from pytorchsim import config, contract
from pytorchsim.backend import compiler_bridge

logger = config.setup_logger()


class ShapeMismatch(RuntimeError):
"""The launch does not match the shapes the binary was compiled for."""


def write_tensor_addrs(workdir, meta, args, launch_dir=None):
"""Write tensor_addrs_file() for Spike (runtime/) or, given `launch_dir`, for TOGSim (there). Refused past the
machine's dram_size; no file (a stale one removed, the reason logged) when a tensor is not an npu one."""
into = contract.runtime_dir(workdir) if launch_dir is None else launch_dir
path = os.path.join(into, tensor_addrs_file())
lines = _get_addr_lines(workdir, meta, args)
if lines is None:
if os.path.exists(path):
os.remove(path)
return None
with open(path, "w") as f:
f.write("".join(lines))
return path


def _get_addr_lines(workdir, meta, args):
"""The file's lines, or None, logged, when some argument is on no npu storage (template timing's CPU zeros)."""
import torch

ko = compiler_bridge.compiler_contract("kernel_object")
pairs = tensor_args(meta, args) if any(torch.is_tensor(a) for a in args) else []
off = [m["name"] for m, t in pairs if t.device.type != "npu"]
if off or not pairs:
logger.info("%s: %s on no npu storage, so no %s and its arguments are laid out from 0",
meta["kernel_name"], ", ".join(off) or "no tensor", ko.TENSOR_ADDRS_FILE)
return None
by_name = {m["name"]: t for m, t in pairs}
target = compiler_bridge.target()
most = torch.npu.sim_address_alignment()
lines = []
for a in contract.kernel_object(workdir)["args"]:
addr, size = torch.npu.sim_address(by_name[a["name"]]), ko.nbytes(a)
if addr + size > target.dram_size:
raise RuntimeError(
f"{meta['kernel_name']}: argument {a['name']} sits at [{addr:#x}, {addr + size:#x}) of simulated "
f"DRAM, past the {target.dram_size:#x} bytes of {target.file}: the npu storages alive now do not "
f"fit that machine")
lines.append(ko.tensor_addr_line(a["name"], addr, size, min(addr & -addr or most, most), a["role"]))
return lines


def tensor_addrs_file():
"""The file a launch's tensor addresses are in, the compiler's kernel_object.TENSOR_ADDRS_FILE."""
return compiler_bridge.compiler_contract("kernel_object").TENSOR_ADDRS_FILE


def tensor_args(meta, args):
"""[(arg_meta, tensor)] for the launch, paired by position: Inductor passes the tensors first,
in signature order, so meta["args"] lines up with the leading arguments."""
import torch

tensors = [a for a in args if isinstance(a, torch.Tensor)]
metas = meta["args"]
if len(tensors) != len(metas):
raise ShapeMismatch(
f"{meta['kernel_name']}: launch passed {len(tensors)} tensor(s), "
f"but the spec declares {len(metas)} ({[m['name'] for m in metas]})")
return list(zip(metas, tensors))
Loading
Loading