From 7f89de672b97853e75ea1fafcaed62ffd5c04adc Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Sun, 8 Nov 2026 23:35:28 +0900 Subject: [PATCH 1/7] [Device] Every npu storage gets a simulated DRAM address from the device allocator The openreg MemoryManager now also allocates each device block a range of a simulated DRAM: from 0, aligned to 16 KiB (XLA's program HBM alignment, what TOGSim lays tensors out at), first fit over the holes freed blocks left, else above everything allocated. orFree frees the range, coalescing it with its neighbours, in the same call that unmaps the host pages and erases the block from the registry, so a host address reused after munmap never inherits an old range. orPointerGetSimAddress gives a device pointer's address: its block's range plus the pointer's offset in the block. The device allocator hands every storage its own block (no caching allocator sits on top), so this is the storage's base plus (data_ptr - storage.data_ptr()), and a buffer Inductor reuses keeps its address. torch.npu.sim_address(tensor) and torch.npu.sim_address_alignment() expose it through the device module's own Python surface; no private torch API is involved. The space is unbounded here: the machine, and with it address_map.dram_size, is known only when a launch is timed, and the timing path refuses a launch whose tensors end past it (the next commit). The timing path's tog_tensor_addrs.txt (next commit) is what reads this; tests/system/test_tensor_placement.py pins both. --- device/third_party/openreg/csrc/memory.cpp | 81 +++++++++++++++++++- device/third_party/openreg/include/openreg.h | 5 ++ device/torch_openreg/csrc/Module.cpp | 20 +++++ device/torch_openreg/openreg/__init__.py | 15 ++++ 4 files changed, 120 insertions(+), 1 deletion(-) 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", From 6bdbeef5d8c702409b88d8f965710c3a4ec21009 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Sun, 8 Nov 2026 23:35:39 +0900 Subject: [PATCH 2/7] [Timing] Each launch tells TOGSim where its tensors are, in tog_tensor_addrs.txt, and an older TOGSim is refused TOGSim laid every launch's tensor arguments out from address 0, so in one session a buffer one kernel wrote sat at another address when the next kernel read it, unrelated tensors shared addresses, and the DRAM channels and the L2 saw that layout. The original PyTorchSim gave TOGSim each tensor's host data_ptr; the trace path had dropped it. run_togsim now writes tog_tensor_addrs.txt into the launch directory beside tog_tensors.txt: one line per kernel object argument in argument order, "name addr bytes align role", addr the simulated DRAM address the device allocator gave the launch tensor's storage plus its offset (torch.npu.sim_address), bytes as tog_tensors.txt states them, align the alignment addr has (at most the allocator's 16 KiB), role the manifest's. Copy nodes get a copy beside theirs. A launch whose argument ends past the machine's address_map.dram_size is refused; a launch that passes no tensor writes none and logs why. Template timing has no host tensors and writes none. get_togsim_command runs Simulator --version once per binary and mtime and refuses anything older than 1.1.0 or of another major (an old Simulator has no --version), so the file is never silently ignored. A session checks before it makes its FIFO. Verified: tests/system/test_tensor_placement.py (new; in CI and the route allowlist) puts a buffer one kernel writes and the next reads at one address in both launches' files, keeps live storages disjoint and reuses a freed range; it fails on dram-trace 5448859 (no file). test_togsim_exit pins the version refusal, and its and test_togsim_result's stub Simulators answer --version. test_launch_record, test_launch_dir, test_copy_node, test_togsim_result, test_togsim_exit, test_one_layer_kv_write pass; Qwen3-0.6B layer decode 128 and prefill 64 run with every launch at given addresses. Needs TOGSim 1.1.0 (TOGSim dram-trace 4d5959a), which PyTorchSim-Triton-Backend dram-trace 3f3e3a28 pins; with the c4a6ee2b image this pin names, the timing path refuses to run until the pin moves. Depends on the previous [Device] commit. --- .github/workflows/pytorchsim_test.yml | 1 + pytorchsim/simulator/timing/__init__.py | 60 +++++++++++++++--- pytorchsim/simulator/timing/togsim.py | 26 +++++++- scripts/ci/triton_route_passing.txt | 1 + tests/system/test_tensor_placement.py | 84 +++++++++++++++++++++++++ tests/system/test_togsim_exit.py | 31 ++++++--- tests/system/test_togsim_result.py | 6 +- 7 files changed, 188 insertions(+), 21 deletions(-) create mode 100644 tests/system/test_tensor_placement.py diff --git a/.github/workflows/pytorchsim_test.yml b/.github/workflows/pytorchsim_test.yml index 1ca3b9f60..83a1a3f6d 100644 --- a/.github/workflows/pytorchsim_test.yml +++ b/.github/workflows/pytorchsim_test.yml @@ -106,6 +106,7 @@ jobs: - tests/system/test_route_allowlist.py - tests/system/test_select.py - tests/system/test_session_cycles.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/pytorchsim/simulator/timing/__init__.py b/pytorchsim/simulator/timing/__init__.py index bd0fd4520..cbe610dc5 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 write_tensor_addrs are the per-launch files TOGSim reads.""" import json import os @@ -20,6 +20,7 @@ SHAPE_TXT = "tog_shape.txt" TENSORS_TXT = "tog_tensors.txt" TENSOR_SHAPES_TXT = "tog_tensor_shapes.txt" +TENSOR_ADDRS_TXT = "tog_tensor_addrs.txt" AXES_TXT = "tog_axes.txt" @@ -59,6 +60,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) + write_tensor_addrs(workdir, meta, args, mine) attribute = attribute_dir(workdir) sim = torch.npu.get_tog_simulator() @@ -103,8 +105,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, TENSOR_ADDRS_TXT): + 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 @@ -240,16 +243,53 @@ 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 write_tensor_addrs(workdir, meta, args, into): + """Write `name addr bytes align role` per kernel argument, in argument order: the simulated DRAM address + the device allocator gave the launch tensor's storage, plus its offset. Refused past the machine's + dram_size; none, with the reason logged, for a launch that passes no tensor.""" + import torch + + from pytorchsim.backend import compiler_bridge + from pytorchsim.simulator import functional + + if not any(torch.is_tensor(a) for a in args): + logger.info("[TOGSim] %s passes no tensor: no %s, TOGSim lays its arguments out from 0", + meta["kernel_name"], TENSOR_ADDRS_TXT) + return None + by_name = {m["name"]: t for m, t in functional.tensor_args(meta, args)} + dram_size = compiler_bridge.target().dram_size + lines = [] + for a in contract.kernel_object(workdir)["args"]: + addr, size = torch.npu.sim_address(by_name[a["name"]]), _get_arg_bytes(a) + if addr + size > dram_size: + raise RuntimeError( + f"{meta['kernel_name']}: argument {a['name']} sits at [{addr:#x}, {addr + size:#x}) of simulated " + f"DRAM, past the {dram_size:#x} bytes of {compiler_bridge.target().file}: the npu storages alive " + f"now do not fit that machine") + align = min(addr & -addr or torch.npu.sim_address_alignment(), torch.npu.sim_address_alignment()) + lines.append(f"{a['name']} {addr} {size} {align} {a['role']}\n") + path = os.path.join(into, TENSOR_ADDRS_TXT) + with open(path, "w") as f: + f.write("".join(lines)) + return path + + +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/togsim.py b/pytorchsim/simulator/timing/togsim.py index dbb3c950f..a584b28eb 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 @@ -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.timing import TENSOR_ADDRS_TXT + 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_TXT} 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]}" diff --git a/scripts/ci/triton_route_passing.txt b/scripts/ci/triton_route_passing.txt index 049392ad6..fb31d7ec0 100644 --- a/scripts/ci/triton_route_passing.txt +++ b/scripts/ci/triton_route_passing.txt @@ -283,3 +283,4 @@ 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_tensor_placement.py 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..a912b97cd 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,13 +23,13 @@ """ -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: @@ -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..43aea28b4 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,7 +33,8 @@ 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: From 03256257c27527d3cca332303185713a27ea6aad Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Tue, 10 Nov 2026 21:02:43 +0900 Subject: [PATCH 3/7] [Functional] Spike is given the tensor addresses TOGSim is: tog_tensor_addrs.txt in each launch's runtime directory The address file is the one per-launch file both simulators read, so it moves out of the timing path into a module of its own, pytorchsim/simulator/placement.py, which functional and timing both import: write_tensor_addrs(workdir, meta, args, launch_dir=None) writes it for Spike into runtime/ beside the .raw files, where the compiler's wrapper reads it and maps each tensor at address_map.dram_base plus its address, or, given launch_dir, for TOGSim into the launch directory beside tog.so. One function produces the lines for both; the file's name and line format are the compiler's kernel_object.TENSOR_ADDRS_FILE and tensor_addr_line. tensor_args and ShapeMismatch move with it, and functional re-exports both under their old names. A launch whose tensors are not npu ones (template timing runs its candidates on CPU zeros) or that passes none gets no file, a stale one removed, and the reason logged: the wrapper and TOGSim then lay the arguments out from 0. tests/system/test_spike_placement.py pins it: the runtime/ file equals the TOGSim launch directory's. On feat/tensor-placement it fails with FileNotFoundError on runtime/tog_tensor_addrs.txt. Measured with PyTorchSim-Triton-Backend feat/spike-placement: Qwen3-0.6B one layer, decode at 128 and prefill at 64, pass; the breakdown's Spike time went 11.27 s to 7.30 s (decode) and 13.86 s to 9.58 s (prefill) against feat/tensor-placement with dram-trace, as read inputs are mapped rather than read(); with the compiler's final wrapper (DRAM mapped whole to the last tensor), run on a node shared with a sweep, 17.28 s and 8.46 s. Qwen3-8B layer decode 1024 passes (max diff 0.0522), and every address its Spike launches print is dram_base plus the address its TOGSim launch was given. Depends on PyTorchSim-Triton-Backend dram-trace (kernel_object.TENSOR_ADDRS_FILE, tensor_addr_line, and the wrapper that reads the file); an older compiler has neither. Arguments that are views of one storage (K and V out of tokenwise pages, q/k/v out of one qkv) now overlap in DRAM, and the wrapper copies their .raw files over each other in argument order. flat_input writes each .raw as the storage's own span from the argument's offset, not zeros between its elements, so every overlapping .raw agrees; zeros there let a later argument zero an earlier one's values (test_fused_sdpa paged_kvcache err 0.83, test_gqa's GQA Attention 0.07). tests/system/test_overlapping_views_spike.py pins it: a * 2 + b over x[:, 0] and x[:, 1] matches the CPU, max abs diff 6.6 with the zero-filled .raw. --- .github/workflows/pytorchsim_test.yml | 1 + pytorchsim/simulator/functional/__init__.py | 44 +++--------- pytorchsim/simulator/placement.py | 74 ++++++++++++++++++++ pytorchsim/simulator/timing/__init__.py | 40 ++--------- pytorchsim/simulator/timing/togsim.py | 4 +- scripts/ci/triton_route_passing.txt | 1 + tests/system/test_overlapping_views_spike.py | 24 +++++++ tests/system/test_spike_placement.py | 35 +++++++++ 8 files changed, 150 insertions(+), 73 deletions(-) create mode 100644 pytorchsim/simulator/placement.py create mode 100644 tests/system/test_overlapping_views_spike.py create mode 100644 tests/system/test_spike_placement.py diff --git a/.github/workflows/pytorchsim_test.yml b/.github/workflows/pytorchsim_test.yml index 83a1a3f6d..58dce1606 100644 --- a/.github/workflows/pytorchsim_test.yml +++ b/.github/workflows/pytorchsim_test.yml @@ -106,6 +106,7 @@ 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 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 cbe610dc5..b2d47c91b 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, write_tensors and write_tensor_addrs 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,7 +8,7 @@ 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() @@ -20,7 +20,6 @@ SHAPE_TXT = "tog_shape.txt" TENSORS_TXT = "tog_tensors.txt" TENSOR_SHAPES_TXT = "tog_tensor_shapes.txt" -TENSOR_ADDRS_TXT = "tog_tensor_addrs.txt" AXES_TXT = "tog_axes.txt" @@ -60,7 +59,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) - write_tensor_addrs(workdir, meta, args, mine) + placement.write_tensor_addrs(workdir, meta, args, launch_dir=mine) attribute = attribute_dir(workdir) sim = torch.npu.get_tog_simulator() @@ -105,7 +104,7 @@ 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, TENSOR_ADDRS_TXT): + 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")) @@ -254,37 +253,6 @@ def write_tensors(workdir, into=None): for a in manifest["args"])) -def write_tensor_addrs(workdir, meta, args, into): - """Write `name addr bytes align role` per kernel argument, in argument order: the simulated DRAM address - the device allocator gave the launch tensor's storage, plus its offset. Refused past the machine's - dram_size; none, with the reason logged, for a launch that passes no tensor.""" - import torch - - from pytorchsim.backend import compiler_bridge - from pytorchsim.simulator import functional - - if not any(torch.is_tensor(a) for a in args): - logger.info("[TOGSim] %s passes no tensor: no %s, TOGSim lays its arguments out from 0", - meta["kernel_name"], TENSOR_ADDRS_TXT) - return None - by_name = {m["name"]: t for m, t in functional.tensor_args(meta, args)} - dram_size = compiler_bridge.target().dram_size - lines = [] - for a in contract.kernel_object(workdir)["args"]: - addr, size = torch.npu.sim_address(by_name[a["name"]]), _get_arg_bytes(a) - if addr + size > dram_size: - raise RuntimeError( - f"{meta['kernel_name']}: argument {a['name']} sits at [{addr:#x}, {addr + size:#x}) of simulated " - f"DRAM, past the {dram_size:#x} bytes of {compiler_bridge.target().file}: the npu storages alive " - f"now do not fit that machine") - align = min(addr & -addr or torch.npu.sim_address_alignment(), torch.npu.sim_address_alignment()) - lines.append(f"{a['name']} {addr} {size} {align} {a['role']}\n") - path = os.path.join(into, TENSOR_ADDRS_TXT) - with open(path, "w") as f: - f.write("".join(lines)) - return path - - def _get_itemsize(arg): import torch return getattr(torch, arg["dtype"]).itemsize diff --git a/pytorchsim/simulator/timing/togsim.py b/pytorchsim/simulator/timing/togsim.py index a584b28eb..eb0e88907 100644 --- a/pytorchsim/simulator/timing/togsim.py +++ b/pytorchsim/simulator/timing/togsim.py @@ -298,7 +298,7 @@ def read_result(result_path): 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.timing import TENSOR_ADDRS_TXT + 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) @@ -311,7 +311,7 @@ def require_placement(bin): 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_TXT} gives instead of laying every launch out from 0. Rebuild TOGSIM_DIR") + f"the address {tensor_addrs_file()} gives instead of laying every launch out from 0. Rebuild TOGSIM_DIR") def _stamp(): diff --git a/scripts/ci/triton_route_passing.txt b/scripts/ci/triton_route_passing.txt index fb31d7ec0..8ae2f35c7 100644 --- a/scripts/ci/triton_route_passing.txt +++ b/scripts/ci/triton_route_passing.txt @@ -283,4 +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") From 66e922a6ee96a2bba08cf7c298a7f002b42f418b Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Mon, 9 Nov 2026 22:43:20 +0900 Subject: [PATCH 4/7] [Timing] tog_axes.txt goes: the TOG refuses a shape_args count it was not compiled for efb39c2 (2026-08-12) wrote the TOG's grid axis count to tog_axes.txt beside a reused tog.so and compared it with each launch's extents, because the TOG then read shape_args[k] without looking at the count the ABI hands it: a launch with one extent too few had it read past the list and loop to the value it found (test_gqa allocated tens of gigabytes). Since TOGSim 1.0.0 (2026-10-22) every TOG the compiler emits reads its shape through togsim::shape, which exits 1 naming both counts when tog_shape.txt gives another number than N, grid extents and scalars together (TOGSim tests/kernels pins it). The file was a second copy of what kernel.json's abi.parallel_axes and the TOG itself state, checked more narrowly, so it and its check are removed; a mismatch now ends the run with TOGSim's message, which the timing path raises as for any TOGSim exit (test_togsim_exit). --- pytorchsim/simulator/timing/__init__.py | 19 ++----------------- 1 file changed, 2 insertions(+), 17 deletions(-) diff --git a/pytorchsim/simulator/timing/__init__.py b/pytorchsim/simulator/timing/__init__.py index b2d47c91b..497469246 100644 --- a/pytorchsim/simulator/timing/__init__.py +++ b/pytorchsim/simulator/timing/__init__.py @@ -21,8 +21,6 @@ TENSORS_TXT = "tog_tensors.txt" TENSOR_SHAPES_TXT = "tog_tensor_shapes.txt" -AXES_TXT = "tog_axes.txt" - LOCK_NAME = ".timing.lock" LOCK_TIMEOUT = 1800 @@ -167,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) @@ -179,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)) @@ -218,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) From 1447d2784c0be01962c542b8a01250bbaf7d0394 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Mon, 9 Nov 2026 16:26:37 +0900 Subject: [PATCH 5/7] [Pin] PyTorchSim-Triton-Backend at its dram-trace tip 72734456, and TOGSim's sidecars by their new names The compiler pin moves from main 087e399b to the dram-trace branch's tip. That tip adds the masked-transfer DMA start and sizing in the TOG and the refusal of a masked start it cannot size, the release-token fix, the PtrAnalysis div and rem fixes, masked-off read rows parked inside their tensor, TOGSim 1.1.0 (tensors at the addresses tog_tensor_addrs.txt gives, sidecars renamed), and the wrapper that maps every tensor at dram_base plus its placement address. The device, timing and functional commits before this one need that compiler and that TOGSim; with the older image the timing path refuses its TOGSim 1.0.0. TOGSim 1.1.0 renames four files beside tog.so and refuses the old names, so the timing path writes and reads them by the new ones: tog_shape.txt -> tog_shape_args.txt, tog_tensors.txt -> tog_tensor_bytes.txt, tog_cycles.tsv -> tog_tile_cycles.tsv, tog_units.tsv -> tog_unit_table.tsv (timing, togsim, gem5, build_identity's stale patterns, and the stub TOGSim directories of test_togsim_exit and test_togsim_result). A workdir cached under the old names has no tables by the new ones, so they are measured again. The image comes from a manual run of that repository's images workflow on dram-trace, which publishes ghcr.io/psal-postech/pytorchsim-triton-backend:- like a main commit's. --- pytorchsim/backend/build_identity.py | 2 +- pytorchsim/simulator/timing/__init__.py | 10 +++++----- pytorchsim/simulator/timing/gem5.py | 2 +- pytorchsim/simulator/timing/togsim.py | 6 +++--- tests/system/test_togsim_exit.py | 2 +- tests/system/test_togsim_result.py | 2 +- third_party/pytorchsim-triton-backend.json | 2 +- 7 files changed, 13 insertions(+), 13 deletions(-) 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/timing/__init__.py b/pytorchsim/simulator/timing/__init__.py index 497469246..49c90bd19 100644 --- a/pytorchsim/simulator/timing/__init__.py +++ b/pytorchsim/simulator/timing/__init__.py @@ -14,11 +14,11 @@ 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" LOCK_NAME = ".timing.lock" @@ -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. """ 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 eb0e88907..eac0a7dc3 100644 --- a/pytorchsim/simulator/timing/togsim.py +++ b/pytorchsim/simulator/timing/togsim.py @@ -239,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: @@ -324,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/tests/system/test_togsim_exit.py b/tests/system/test_togsim_exit.py index a912b97cd..42037be08 100644 --- a/tests/system/test_togsim_exit.py +++ b/tests/system/test_togsim_exit.py @@ -36,7 +36,7 @@ def _checkout(root, status, version=VERSION): 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/tests/system/test_togsim_result.py b/tests/system/test_togsim_result.py index 43aea28b4..44fd0f760 100644 --- a/tests/system/test_togsim_result.py +++ b/tests/system/test_togsim_result.py @@ -41,7 +41,7 @@ def _checkout(root, writes=True): 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..c68580f55 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": "7273445606ab90406633bd0e50bd5afe9d3e1dd5" } } From 4908a3c05f38b650d95c3d8ee9aa55792b797074 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Wed, 11 Nov 2026 04:29:48 +0900 Subject: [PATCH 6/7] [Pin] PyTorchSim-Triton-Backend at main 2171fad6, the merge of the dram-trace commits the previous pin named PyTorchSim-Triton-Backend#396-#400 landed the dram-trace tip's commits on main, so the pin moves from that branch to main, where the images workflow publishes the base image. TOGSim comes along as main's third_party/TOGSim submodule, 7a35ffc (TOGSim#70). --- third_party/pytorchsim-triton-backend.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/third_party/pytorchsim-triton-backend.json b/third_party/pytorchsim-triton-backend.json index c68580f55..7ed7bff20 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": "7273445606ab90406633bd0e50bd5afe9d3e1dd5" + "ref": "2171fad600661cbc488cb6f9033ae4260de3e875" } } From efa30a29ec96f155c817b7e8358dbe6da32afa61 Mon Sep 17 00:00:00 2001 From: student-Jungmin Date: Wed, 11 Nov 2026 11:28:10 +0900 Subject: [PATCH 7/7] [Pin] PyTorchSim-Triton-Backend at main d02b86f1, the last main commit with a published runtime image 2171fad6's images run never published -runtime: its simulate layer shard died on a runner with a full disk, so the manifest job was skipped. d02b86f1 (the merge of PyTorchSim-Triton-Backend#399) has the image and pins TOGSim at 7a35ffc. It lacks only #400 (kernel functions page-aligned, so gem5 tile cycles stop moving with the wrapper's size); values are unaffected, tile cycles may shift until the next pin bump brings it in. --- third_party/pytorchsim-triton-backend.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/third_party/pytorchsim-triton-backend.json b/third_party/pytorchsim-triton-backend.json index 7ed7bff20..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": "2171fad600661cbc488cb6f9033ae4260de3e875" + "ref": "d02b86f103195e6bb9c4e7e89487c410ac9c44d5" } }