diff --git a/.github/workflows/pytorchsim_test.yml b/.github/workflows/pytorchsim_test.yml index 1ca3b9f60..58dce1606 100644 --- a/.github/workflows/pytorchsim_test.yml +++ b/.github/workflows/pytorchsim_test.yml @@ -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 diff --git a/device/third_party/openreg/csrc/memory.cpp b/device/third_party/openreg/csrc/memory.cpp index 6f02eeb05..525f144d9 100644 --- a/device/third_party/openreg/csrc/memory.cpp +++ b/device/third_party/openreg/csrc/memory.cpp @@ -2,6 +2,8 @@ #include +#include +#include #include #include @@ -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 m_holes; + uint64_t m_top = 0; }; class MemoryManager { @@ -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; } @@ -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 { @@ -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 lock(m_mutex); + Block* info = getBlockInfoNoLock(ptr); + if (!info || info->type != orMemoryType::orMemoryTypeDevice) + return orErrorUnknown; + *addr = info->sim_addr + static_cast(static_cast(ptr) - + static_cast(info->pointer)); + return orSuccess; + } + orError_t unprotect(void* ptr) { std::lock_guard lock(m_mutex); return unprotectNoLock(getBlockInfoNoLock(ptr)); @@ -197,6 +267,7 @@ class MemoryManager { } std::map m_registry; + SimDram m_sim_dram; std::mutex m_mutex; }; @@ -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); } diff --git a/device/third_party/openreg/include/openreg.h b/device/third_party/openreg/include/openreg.h index a5e4af558..4df907e98 100644 --- a/device/third_party/openreg/include/openreg.h +++ b/device/third_party/openreg/include/openreg.h @@ -1,6 +1,7 @@ #pragma once #include +#include #ifdef _WIN32 #define OPENREG_EXPORT __declspec(dllexport) @@ -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); diff --git a/device/torch_openreg/csrc/Module.cpp b/device/torch_openreg/csrc/Module.cpp index e4f3e8d1f..ea5d238c5 100644 --- a/device/torch_openreg/csrc/Module.cpp +++ b/device/torch_openreg/csrc/Module.cpp @@ -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(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}, @@ -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}}; /* diff --git a/device/torch_openreg/openreg/__init__.py b/device/torch_openreg/openreg/__init__.py index e46649aa7..6612e3013 100644 --- a/device/torch_openreg/openreg/__init__.py +++ b/device/torch_openreg/openreg/__init__.py @@ -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 @@ -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", diff --git a/pytorchsim/backend/build_identity.py b/pytorchsim/backend/build_identity.py index dcc9b9111..804b08ac1 100644 --- a/pytorchsim/backend/build_identity.py +++ b/pytorchsim/backend/build_identity.py @@ -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 diff --git a/pytorchsim/simulator/functional/__init__.py b/pytorchsim/simulator/functional/__init__.py index f809b9401..466a53502 100644 --- a/pytorchsim/simulator/functional/__init__.py +++ b/pytorchsim/simulator/functional/__init__.py @@ -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.""" @@ -49,8 +46,8 @@ def run(workdir, meta, args): def write_inputs(workdir, meta, args): - """Write every arg as runtime/.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/.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 @@ -58,6 +55,7 @@ def write_inputs(workdir, 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"): @@ -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): @@ -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"]: diff --git a/pytorchsim/simulator/placement.py b/pytorchsim/simulator/placement.py new file mode 100644 index 000000000..104ab6186 --- /dev/null +++ b/pytorchsim/simulator/placement.py @@ -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)) diff --git a/pytorchsim/simulator/timing/__init__.py b/pytorchsim/simulator/timing/__init__.py index bd0fd4520..49c90bd19 100644 --- a/pytorchsim/simulator/timing/__init__.py +++ b/pytorchsim/simulator/timing/__init__.py @@ -1,6 +1,6 @@ """The timing path: the compiler's tile-operation graph (tog.so) -> TOGSim. run writes the cycle tables if needed (write_cycle_tables: tog.so + gem5's sampled tiles) and simulates (run_togsim); -write_shape and write_tensors are the per-launch files TOGSim reads.""" +write_shape, write_tensors and placement.write_tensor_addrs are the per-launch files TOGSim reads.""" import json import os @@ -8,21 +8,19 @@ from pytorchsim import config, contract from pytorchsim.backend import compiler_bridge -from pytorchsim.simulator import wallclock +from pytorchsim.simulator import placement, wallclock from pytorchsim.simulator.timing import gem5 logger = config.setup_logger() TOG_SO = "tog.so" -CYCLE_TSV = "tog_cycles.tsv" -UNITS_TSV = "tog_units.tsv" +CYCLE_TSV = "tog_tile_cycles.tsv" +UNITS_TSV = "tog_unit_table.tsv" SHARED = (TOG_SO, CYCLE_TSV, UNITS_TSV) -SHAPE_TXT = "tog_shape.txt" -TENSORS_TXT = "tog_tensors.txt" +SHAPE_TXT = "tog_shape_args.txt" +TENSORS_TXT = "tog_tensor_bytes.txt" TENSOR_SHAPES_TXT = "tog_tensor_shapes.txt" -AXES_TXT = "tog_axes.txt" - LOCK_NAME = ".timing.lock" LOCK_TIMEOUT = 1800 @@ -59,6 +57,7 @@ def run_togsim(workdir, meta, args=(), names=None): mine = contract.new_launch_dir(workdir, SHARED, build_launch_record(meta, args, names)) write_shape(workdir, meta, args, mine) write_tensors(workdir, mine) + placement.write_tensor_addrs(workdir, meta, args, launch_dir=mine) attribute = attribute_dir(workdir) sim = torch.npu.get_tog_simulator() @@ -103,8 +102,9 @@ def copy_node_handles(workdir, mine): os.symlink(so, os.path.join(d, TOG_SO)) for name in (CYCLE_TSV, UNITS_TSV): open(os.path.join(d, name), "w").close() - for name in (TENSORS_TXT, TENSOR_SHAPES_TXT): - shutil.copyfile(os.path.join(mine, name), os.path.join(d, name)) + for name in (TENSORS_TXT, TENSOR_SHAPES_TXT, placement.tensor_addrs_file()): + if os.path.isfile(os.path.join(mine, name)): + shutil.copyfile(os.path.join(mine, name), os.path.join(d, name)) handles.append(os.path.join(d, "tile_graph.onnx")) return handles @@ -149,7 +149,7 @@ def _held_for_the_session(sim, mine, attribute): def write_cycle_tables(workdir, meta): - """Place the compiler's tog.so in the workdir and write tog_cycles.tsv and tog_units.tsv beside it. + """Place the compiler's tog.so in the workdir and write tog_tile_cycles.tsv and tog_unit_table.tsv beside it. Returns the number of compute tiles gem5 measured. """ @@ -165,7 +165,6 @@ def write_cycle_tables(workdir, meta): with open(types_path) as fh: tiles = json.load(fh) offsets = tiles["overlap_offset"] - axes = tiles["parallel_axes"] n_tiles = len(offsets) m5out = gem5.run_cycle_binary(workdir, meta) @@ -177,9 +176,6 @@ def write_cycle_tables(workdir, meta): if os.path.abspath(so_path) != os.path.abspath(os.path.join(workdir, TOG_SO)): shutil.copyfile(so_path, os.path.join(workdir, TOG_SO)) - with open(os.path.join(workdir, AXES_TXT), "w") as f: - f.write(f"{len(axes)}\n") - with open(os.path.join(workdir, UNITS_TSV), "w") as f: f.write("".join("\t".join(str(v) for v in r) + "\n" for r in rows)) gem5.dump_cycle_table_tsv(table, os.path.join(workdir, CYCLE_TSV)) @@ -216,17 +212,8 @@ def write_shape(workdir, meta, args=(), into=None): def _write_extents(workdir, ext, what, meta, args, into=None): """Write `ext` and the launch's integer scalars as this launch's shape_args in its launch - directory (`into`, else this process's), refusing a grid count the shared TOG cannot use.""" - path = os.path.join(workdir, AXES_TXT) - if os.path.isfile(path): - with open(path) as f: - want = int(f.read().strip()) - if want != len(ext): - raise ValueError( - f"{TOG_SO} in {workdir} was compiled to read {want} grid " - f"extent(s) and this launch has {len(ext)} ({ext}); the TOG " - f"would read past the end of shape_args. Delete the workdir to " - f"rebuild it.") + directory (`into`, else this process's). A count the TOG was not compiled for is refused by the TOG itself + (togsim::shape), before it reads past shape_args.""" ko = compiler_bridge.compiler_contract("kernel_object") shape = ko.shape_args(contract.kernel_object(workdir), dict(zip(meta.get("call_params", ()), args)), grid=ext) @@ -240,16 +227,22 @@ def write_tensors(workdir, into=None): axis folded into the rows, in argument order, where TOGSim reads them to lay it out in DRAM.""" import math - import torch - - manifest = contract.kernel_object(workdir) if manifest is None: raise FileNotFoundError(f"{workdir} has no kernel.json -- compile the kernel first") - args = [(a["shape"], getattr(torch, a["dtype"]).itemsize) for a in manifest["args"]] into = into or contract.dir_for(workdir) with open(os.path.join(into, TENSORS_TXT), "w") as f: - f.write("".join(f"{math.prod(shape) * elem}\n" for shape, elem in args)) + f.write("".join(f"{_get_arg_bytes(a)}\n" for a in manifest["args"])) with open(os.path.join(into, TENSOR_SHAPES_TXT), "w") as f: - f.write("".join(f"{math.prod(shape[:-1])} {shape[-1] if shape else 1} {elem}\n" - for shape, elem in args)) + f.write("".join(f"{math.prod(a['shape'][:-1])} {a['shape'][-1] if a['shape'] else 1} {_get_itemsize(a)}\n" + for a in manifest["args"])) + + +def _get_itemsize(arg): + import torch + return getattr(torch, arg["dtype"]).itemsize + + +def _get_arg_bytes(arg): + import math + return math.prod(arg["shape"]) * _get_itemsize(arg) diff --git a/pytorchsim/simulator/timing/gem5.py b/pytorchsim/simulator/timing/gem5.py index a23f72a5e..1e1137b6c 100644 --- a/pytorchsim/simulator/timing/gem5.py +++ b/pytorchsim/simulator/timing/gem5.py @@ -1,5 +1,5 @@ """gem5 over the compiler's cycle binary, one sampled tile per dump, and the tables TOGSim reads -beside the TOG from those dumps: tog_cycles.tsv (cycle, overlapping) and tog_units.tsv.""" +beside the TOG from those dumps: tog_tile_cycles.tsv (cycle, overlapping) and tog_unit_table.tsv.""" import os import re diff --git a/pytorchsim/simulator/timing/togsim.py b/pytorchsim/simulator/timing/togsim.py index dbb3c950f..eac0a7dc3 100644 --- a/pytorchsim/simulator/timing/togsim.py +++ b/pytorchsim/simulator/timing/togsim.py @@ -16,6 +16,9 @@ logger = config.setup_logger() +#: The first TOGSim that places a launch's tensors at the addresses tog_tensor_addrs.txt gives. +PLACEMENT_VERSION = (1, 1, 0) +_VERSIONS = {} class Cut(RuntimeError): @@ -68,6 +71,7 @@ def __init__(self, config_path=None, togsim_path=None) -> None: self.config_path = config_path if not os.path.isfile(self.config_path): raise FileNotFoundError(f"machine file not found: {self.config_path}") + self._command = self.get_togsim_command(self.config_path, self.base_dir) self.process = None self.held = [] self._next_kernel_id = 0 @@ -95,7 +99,7 @@ def __init__(self, config_path=None, togsim_path=None) -> None: raise RuntimeError(f"Failed to open trace file: {e}") def _start_process(self): - cmd = (f"{self.get_togsim_command(self.config_path, self.base_dir)} --models_list {self.trace_file_path}" + cmd = (f"{self._command} --models_list {self.trace_file_path}" f" --result {self.result_path}") if config.CONFIG_TOGSIM_DEBUG_LEVEL: cmd += f" --log_level {config.CONFIG_TOGSIM_DEBUG_LEVEL}" @@ -193,6 +197,7 @@ def get_togsim_command(config_path, togsim_path=None): raise FileNotFoundError( f"{bin} not found: TOGSIM_DIR must name a TOGSim checkout that has been built " f"(the compiler's setup/toolchain.sh togsim builds the one it carries)") + require_placement(bin) config_file = os.path.join(togsim_path, config_path) cmd = f"{bin} --config {config_file}" return cmd @@ -234,11 +239,11 @@ def run_standalone( try: tog_so = os.path.join(os.path.dirname(str(model_path)), "tog.so") - cycle_tsv = os.path.join(os.path.dirname(str(model_path)), "tog_cycles.tsv") + cycle_tsv = os.path.join(os.path.dirname(str(model_path)), "tog_tile_cycles.tsv") if not os.path.exists(tog_so): raise FileNotFoundError(f"{tog_so} not found -- the kernel has no TOG to simulate") base_cmd = TOGSimProcess.get_togsim_command(config_path, togsim_path) - unit_tsv = os.path.join(os.path.dirname(str(model_path)), "tog_units.tsv") + unit_tsv = os.path.join(os.path.dirname(str(model_path)), "tog_unit_table.tsv") cmd = (f"{base_cmd} --tog_so {tog_so} --cycle_table {cycle_tsv} --unit_table {unit_tsv}" f" --result {result_path}") if attribute_path: @@ -290,6 +295,25 @@ def read_result(result_path): return json.load(f) +def require_placement(bin): + """Refuse a Simulator older than PLACEMENT_VERSION, which ignores tog_tensor_addrs.txt and lays every + launch's tensors out from 0; what `bin --version` printed is kept per binary and mtime.""" + from pytorchsim.simulator.placement import tensor_addrs_file + key = (bin, os.path.getmtime(bin)) + if key not in _VERSIONS: + got = subprocess.run([bin, "--version"], capture_output=True, text=True) + said = got.stdout.strip().split(".") + _VERSIONS[key] = tuple(int(v) for v in said) if got.returncode == 0 and all( + v.isdigit() for v in said) and len(said) == 3 else None + have = _VERSIONS[key] + if have is None or have[0] != PLACEMENT_VERSION[0] or have < PLACEMENT_VERSION: + shown = "no version (it has no --version)" if have is None else ".".join(map(str, have)) + raise RuntimeError( + f"{bin} reports {shown}; the timing path needs TOGSim " + f"{'.'.join(map(str, PLACEMENT_VERSION))} or newer of the same major, which places each tensor at " + f"the address {tensor_addrs_file()} gives instead of laying every launch out from 0. Rebuild TOGSIM_DIR") + + def _stamp(): """The name a run's .log, .trace and .json share: when it started, and a random suffix.""" return datetime.datetime.now().strftime('%Y%m%d_%H%M%S') + f"_{uuid.uuid4().hex[:8]}" @@ -300,7 +324,7 @@ def _stamp(): import argparse ap = argparse.ArgumentParser(description="Send kernels to TOGSim directly.") - ap.add_argument("kernel_dir", help="directory holding tog.so and tog_cycles.tsv") + ap.add_argument("kernel_dir", help="directory holding tog.so and tog_tile_cycles.tsv") ap.add_argument("attribute", help="kernel attribute file") ap.add_argument("--config", default=None, help="TOGSim hardware YAML") ap.add_argument("--repeat", type=int, default=1) diff --git a/scripts/ci/triton_route_passing.txt b/scripts/ci/triton_route_passing.txt index 049392ad6..8ae2f35c7 100644 --- a/scripts/ci/triton_route_passing.txt +++ b/scripts/ci/triton_route_passing.txt @@ -283,3 +283,5 @@ tests/system/test_bundle_reuse.py tests/system/test_eager.py tests/system/test_launch_record.py tests/system/test_session_cycles.py +tests/system/test_spike_placement.py +tests/system/test_tensor_placement.py diff --git a/tests/system/test_overlapping_views_spike.py b/tests/system/test_overlapping_views_spike.py new file mode 100644 index 000000000..ca0777387 --- /dev/null +++ b/tests/system/test_overlapping_views_spike.py @@ -0,0 +1,24 @@ +"""Two kernel arguments that are interleaved views of one storage (K and V out of tokenwise pages, q/k/v out of +one qkv) read their own values on Spike. Breaks when an argument's .raw holds zeros between its elements: the +wrapper copies overlapping .raw files over each other, and the later one zeroes the earlier one's values.""" +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 # noqa: E402 + + +def test_interleaved_views_of_one_storage(): + torch._dynamo.reset() + x = torch.randn(1024, 2) + f = torch.compile(lambda a, b: a * 2 + b, dynamic=False) + dev = x.to("npu:0") + got = f(dev[:, 0], dev[:, 1]) + check_result("interleaved views", got.cpu(), x[:, 0] * 2 + x[:, 1]) + + +if __name__ == "__main__": + test_interleaved_views_of_one_storage() + print("Test Passed") diff --git a/tests/system/test_spike_placement.py b/tests/system/test_spike_placement.py new file mode 100644 index 000000000..0244677d6 --- /dev/null +++ b/tests/system/test_spike_placement.py @@ -0,0 +1,35 @@ +"""A launch's runtime/ holds the tog_tensor_addrs.txt its TOGSim launch directory does, so the wrapper Spike +runs puts every tensor where TOGSim puts it. Breaks when functional.write_inputs stops writing it, or writes +lines of its own instead of placement.write_tensor_addrs's.""" +import os +import sys + +os.environ["TORCHSIM_TIMING_MODE"] = "1" +sys.path.insert(0, os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim")) + +import torch # noqa: E402 + +from pytorchsim import contract # noqa: E402 +from test_tensor_placement import ADDRS, _launch_dirs # noqa: E402 + + +def test_spike_is_given_the_addresses_togsim_is(): + device = torch.device("npu:0") + a = torch.randn(64, 256).to(device) + view = torch.randn(96, 256).to(device)[32:] + read = torch.compile(lambda a, v: a * 2.0 + v, dynamic=False) + with torch.no_grad(), torch.npu.TOGSimulator() as sim: + y = read(a, view) + torch.testing.assert_close(y.cpu(), a.cpu() * 2.0 + view.cpu()) + (launch,) = _launch_dirs(sim.trace_path) + runtime = contract.runtime_dir(os.path.dirname(launch)) + with open(os.path.join(launch, ADDRS)) as f: + togsim = f.read() + with open(os.path.join(runtime, ADDRS)) as f: + spike = f.read() + assert spike == togsim, (spike, togsim) + + +if __name__ == "__main__": + test_spike_is_given_the_addresses_togsim_is() + print("PASS") diff --git a/tests/system/test_tensor_placement.py b/tests/system/test_tensor_placement.py new file mode 100644 index 000000000..646e05b57 --- /dev/null +++ b/tests/system/test_tensor_placement.py @@ -0,0 +1,84 @@ +"""In one TOGSim session kernel A writes x and kernel B reads it: both launches' tog_tensor_addrs.txt place +x at torch.npu.sim_address(x), live storages never overlap and a freed storage's range is reused. Breaks when +TOGSim gets no addresses, the allocator forgets a free, or addresses are host pointers or 0 per launch.""" +import os +import sys + +os.environ["TORCHSIM_TIMING_MODE"] = "1" +sys.path.insert(0, os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim")) + +import torch # noqa: E402 + +ADDRS = "tog_tensor_addrs.txt" + + +def _launch_dirs(trace_path): + """Each launch's directory in a session's trace, in order; a copy node's is its kernel's.""" + out = [] + with open(trace_path) as f: + for line in f: + if line.startswith("LAUNCH_KERNEL"): + d = os.path.dirname(line.split(",")[4]) + while d != "/" and not os.path.basename(d).startswith("launch-"): + d = os.path.dirname(d) + if d not in out: + out.append(d) + return out + + +def _addrs(launch_dir): + """{role: [(addr, bytes)]} of a launch's tog_tensor_addrs.txt.""" + out = {} + with open(os.path.join(launch_dir, ADDRS)) as f: + for line in f: + name, addr, size, align, role = line.split() + assert int(addr) % int(align) == 0, line + out.setdefault(role, []).append((int(addr), int(size))) + return out + + +def _range(t): + return torch.npu.sim_address(t), t.untyped_storage().nbytes() + + +def _disjoint(ranges): + ranges = sorted(ranges) + return all(a + n <= b for (a, n), (b, _) in zip(ranges, ranges[1:])) + + +def test_a_written_buffer_is_read_at_its_address(): + device = torch.device("npu:0") + a = torch.randn(64, 256).to(device) + write = torch.compile(lambda a: a + 1.0, dynamic=False) + read = torch.compile(lambda x: x * 2.0, dynamic=False) + with torch.no_grad(), torch.npu.TOGSimulator() as sim: + x = write(a) + y = read(x) + torch.testing.assert_close(y.cpu(), (a.cpu() + 1.0) * 2.0) + first, second = (_addrs(d) for d in _launch_dirs(sim.trace_path)) + x_at = (torch.npu.sim_address(x), x.numel() * x.element_size()) + assert first["out"] == [x_at] and second["in"] == [x_at], (first, second, x_at) + assert first["in"] == [(torch.npu.sim_address(a), a.numel() * 4)], first + assert _disjoint([_range(a), _range(x), _range(y)]), [_range(t) for t in (a, x, y)] + + +def test_live_storages_never_overlap_and_a_freed_range_is_reused(): + device = torch.device("npu:0") + align = torch.npu.sim_address_alignment() + live = [torch.empty(n, device=device) for n in (1, 4096, 4097, 300000, 7)] + assert _disjoint([_range(t) for t in live]), [_range(t) for t in live] + assert all(torch.npu.sim_address(t) % align == 0 for t in live) + view = live[3][128:] + assert torch.npu.sim_address(view) == torch.npu.sim_address(live[3]) + 128 * 4 + big = torch.empty(16 << 20, device=device) + at = torch.npu.sim_address(big) + del big + again = torch.empty(16 << 20, device=device) + assert torch.npu.sim_address(again) == at, (torch.npu.sim_address(again), at) + assert _disjoint([_range(t) for t in live + [again]]) + + +if __name__ == "__main__": + test_a_written_buffer_is_read_at_its_address() + test_live_storages_never_overlap_and_a_freed_range_is_reused() + print("PASS") diff --git a/tests/system/test_togsim_exit.py b/tests/system/test_togsim_exit.py index 30c044e75..42037be08 100644 --- a/tests/system/test_togsim_exit.py +++ b/tests/system/test_togsim_exit.py @@ -1,6 +1,6 @@ -"""A Simulator that exits non-zero is a RuntimeError on both paths: run_standalone carries its last -line, shutdown its status; a session on a machine file that is not there is refused before it starts. -The Simulator here is a stub, so no TOGSim is needed.""" +"""A Simulator that exits non-zero is a RuntimeError on both paths: run_standalone carries its last line, +shutdown its status; a session on a machine file that is not there, or a Simulator older than 1.1.0, is +refused before it starts. The Simulator here is a stub, so no TOGSim is needed.""" import os import stat import sys @@ -10,10 +10,12 @@ sys.path.insert(0, os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim")) from pytorchsim import config -from pytorchsim.simulator.timing.togsim import TOGSimProcess +from pytorchsim.simulator.timing.togsim import PLACEMENT_VERSION, TOGSimProcess REFUSAL = "[error] [TOGSim] TOG k/tog.so: work-item 0 (key 10) needs 49153 bytes in the spad at once" +VERSION = "{ echo %s; exit 0; }" % ".".join(map(str, PLACEMENT_VERSION)) STUB = """#!/bin/sh +[ "$1" = --version ] && {version} while [ $# -gt 0 ]; do [ "$1" = --models_list ] && cat "$2" > /dev/null; shift; done echo "[info] [TOGSim] loading" echo "{refusal}" @@ -21,20 +23,20 @@ """ -def _checkout(root, status): - """A TOGSim checkout whose Simulator drains its command stream, prints REFUSAL and exits `status`, - and a machine file in it; the simulator is handed both explicitly.""" +def _checkout(root, status, version=VERSION): + """A TOGSim checkout whose Simulator answers --version by `version`, drains its command stream, prints + REFUSAL and exits `status`, and a machine file in it; the simulator is handed both explicitly.""" os.makedirs(os.path.join(root, "build", "bin")) simulator = config.togsim_simulator(root) with open(simulator, "w") as f: - f.write(STUB.format(refusal=REFUSAL, status=status)) + f.write(STUB.format(refusal=REFUSAL, status=status, version=version)) os.chmod(simulator, os.stat(simulator).st_mode | stat.S_IXUSR) machine = os.path.join(root, "machine.yml") with open(machine, "w") as f: f.write("core_freq_mhz: 1\n") kernel = os.path.join(root, "k") os.makedirs(kernel) - for name in ("tog.so", "tog_cycles.tsv", "tog_units.tsv"): + for name in ("tog.so", "tog_tile_cycles.tsv", "tog_unit_table.tsv"): open(os.path.join(kernel, name), "w").close() return machine, os.path.join(kernel, "tile_graph.onnx"), os.path.join(kernel, "attribute") @@ -89,6 +91,18 @@ def test_session_on_a_missing_machine_file_is_refused(): raise AssertionError("a session started on a machine file that is not there") +def test_a_simulator_older_than_placement_is_refused(): + for version, shown in (("{ echo 1.0.0; exit 0; }", "reports 1.0.0"), + ("{ echo unrecognised option >&2; exit 1; }", "reports no version")): + with tempfile.TemporaryDirectory() as root, _logs_in(root): + machine, handle, attribute = _checkout(root, 0, version) + said = _raised(lambda: TOGSimProcess(config_path=machine, togsim_path=root)) + assert said is not None and shown in said and "tog_tensor_addrs.txt" in said, said + said = _raised(lambda: TOGSimProcess.run_standalone( + handle, attribute, autotune_mode=True, config_path=machine, togsim_path=root)) + assert said is not None and shown in said, said + + def test_environment_is_left_as_found(): """No TOGSIM_CONFIG (which the compiler bridge refuses) or log path outlives a test here.""" before = dict(os.environ) @@ -102,5 +116,6 @@ def test_environment_is_left_as_found(): test_session_refusal_is_a_runtime_error() test_session_that_ran_shuts_down_quietly() test_session_on_a_missing_machine_file_is_refused() + test_a_simulator_older_than_placement_is_refused() test_environment_is_left_as_found() print("PASS") diff --git a/tests/system/test_togsim_result.py b/tests/system/test_togsim_result.py index 277d7e337..44fd0f760 100644 --- a/tests/system/test_togsim_result.py +++ b/tests/system/test_togsim_result.py @@ -12,11 +12,12 @@ from pytorchsim import config from pytorchsim.backend import codecache from pytorchsim.simulator import timing -from pytorchsim.simulator.timing.togsim import TOGSimProcess +from pytorchsim.simulator.timing.togsim import PLACEMENT_VERSION, TOGSimProcess RESULT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "togsim_tpuv6e.json") SAID = "[info] [TOGSim] the stub ran" STUB = """#!/bin/sh +[ "$1" = --version ] && {{ echo {version}; exit 0; }} echo "{said}" while [ $# -gt 0 ]; do [ "$1" = --models_list ] && cat "$2" > /dev/null @@ -32,14 +33,15 @@ def _checkout(root, writes=True): os.makedirs(os.path.join(root, "build", "bin")) simulator = config.togsim_simulator(root) with open(simulator, "w") as f: - f.write(STUB.format(said=SAID, write=f'cp {RESULT} "$2"' if writes else "true")) + f.write(STUB.format(said=SAID, write=f'cp {RESULT} "$2"' if writes else "true", + version=".".join(map(str, PLACEMENT_VERSION)))) os.chmod(simulator, os.stat(simulator).st_mode | stat.S_IXUSR) machine = os.path.join(root, "machine.yml") with open(machine, "w") as f: f.write("core_freq_mhz: 1\n") kernel = os.path.join(root, "k") os.makedirs(kernel) - for name in ("tog.so", "tog_cycles.tsv", "tog_units.tsv"): + for name in ("tog.so", "tog_tile_cycles.tsv", "tog_unit_table.tsv"): open(os.path.join(kernel, name), "w").close() return machine, os.path.join(kernel, "tile_graph.onnx"), os.path.join(kernel, "attribute") diff --git a/third_party/pytorchsim-triton-backend.json b/third_party/pytorchsim-triton-backend.json index 5d63ec071..a69d9ed65 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": "087e399b3e04336662711154fddc3bf42c950782" + "ref": "d02b86f103195e6bb9c4e7e89487c410ac9c44d5" } }