diff --git a/.github/workflows/pytorchsim_triton_backend.yml b/.github/workflows/pytorchsim_triton_backend.yml index 0fbf834f8..58391d840 100644 --- a/.github/workflows/pytorchsim_triton_backend.yml +++ b/.github/workflows/pytorchsim_triton_backend.yml @@ -2,7 +2,6 @@ name: Triton codegen route (PyTorchSim-Triton-Backend) # Exercises the Triton codegen route: Inductor's own Triton backend produces the # kernel and PyTorchSim-Triton-Backend lowers it to a RISC-V ELF. -# (PyTorchSimFrontend/triton_backend/README.md) # # Separate from the main CI on purpose: it runs when the compiler pin moves, and # its sweep reports rather than gates. diff --git a/.gitmodules b/.gitmodules index 24f9ccaf6..c57f58613 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,15 +1,6 @@ -[submodule "TOGSim/extern/onnx"] - path = TOGSim/extern/onnx - url = https://github.com/onnx/onnx.git -[submodule "TOGSim/extern/protobuf"] - path = TOGSim/extern/protobuf - url = https://github.com/protocolbuffers/protobuf.git [submodule "TOGSim/extern/booksim"] path = TOGSim/extern/booksim url = https://github.com/PSAL-POSTECH/booksim.git [submodule "TOGSim/extern/ramulator2"] path = TOGSim/extern/ramulator2 url = https://github.com/PSAL-POSTECH/ramulator2 -[submodule "TOGSim/extern/stonneCore"] - path = TOGSim/extern/stonneCore - url = https://github.com/PSAL-POSTECH/stonne_core.git diff --git a/CLAUDE.md b/CLAUDE.md index dc503ee27..043a81875 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -68,9 +68,9 @@ report next to the number it produced — never folded into a pass. |---|---| | `PyTorchSimFrontend/` | Python compiler stack (Inductor backend). `extension_config.py` is the central settings reader; `triton_backend/` is the `npu` codegen route (Inductor's Triton backend, the compiler bridge, and `trace_build.py` -- the gem5/g++ half of the TOGSim trace) | | `PyTorchSimDevice/` | C++ PyTorch backend registering the `npu` device. Built as a pip-installed package via `setup.py`. Based on `torch_openreg` (PrivateUse1 example). Produces `_C.cpython-*.so` | -| `Simulator/simulator.py` | Python drivers: `CycleSimulator` (Gem5), `TOGSimulator` (the cycle-accurate one + multi-tenant context manager). Spike is driven by `triton_backend/functional.py` | +| `Simulator/simulator.py` | `TOGSimulator`: the TOGSim process driver and multi-tenant context manager. gem5 is driven by `triton_backend/gem5.py` (`CycleSimulator`), Spike by `triton_backend/spike_run.py` | | `Scheduler/scheduler.py` | Poisson arrival generator + scheduling utilities for multi-tenant runs | -| `TOGSim/` | C++ TOGSim source. `src/Simulator.cc`, `Core.cc`, `Dram.cc`, `Interconnect.cc`, `L2Cache.cc`, `Tile.cc`, `TileGraph.cc` are the core models. Externals: ramulator2, booksim, stonneCore, onnx, protobuf, spdlog, yaml-cpp | +| `TOGSim/` | C++ TOGSim source. `src/Simulator.cc`, `Core.cc`, `Dram.cc`, `Interconnect.cc`, `L2Cache.cc`, `Tile.cc`, `TileGraph.cc` are the core models. Externals: ramulator2, booksim, spdlog, yaml-cpp | | `configs/` | TOGSim hardware configs (YAML). The default is `systolic_ws_256x256_c1_simple_noc_tpuv6e_functional_only.yml` -- the same machine as `..._tpuv6e.yml` and one line apart, `pytorchsim_timing_mode: 0`. Naming pattern: `systolic_ws__c__.yml` | | `tests/` | Op- and model-level tests organized under `ops//` (elementwise, reduce, gemm, conv, attention, view, sort, sparsity, misc, fusion), `models//` (Llama, Mixtral8x7B, DeepSeek, Diffusion, MoE, MLP, MobileNet, Yolov5) plus single-file model tests (test_resnet, test_transformer, test_vit, test_mlp, test_single_perceptron), and `system/` (scheduler, eager, vectorops). Shared helper: `tests/_utils.py`. **Which of them pass is `scripts/ci/triton_route_passing.txt`**; the rest are known gaps, swept and reported by `scripts/ci/triton_route_sweep.py --all` | | `experiments/artifact/` | Paper reproduction scripts (`cycle_validation/run_cycle.sh`, `speedup/run_speedup.sh`) | @@ -94,7 +94,7 @@ Run a model from `tests/models/Llama/`, `tests/models/DeepSeek/`, etc. similarly **CI coverage:** `.github/workflows/docker-image.yml` is the PR gate. It builds the base image, then the PyTorchSim-Triton-Backend layer (`Dockerfile.ptb`, pinned by `thirdparty/pytorchsim-triton-backend.json`: the compiler plus the vcix-accelerator RISC-V toolchain, pk, Spike and gem5), then the app image, and calls `.github/workflows/pytorchsim_test.yml` once per hardware config. That workflow is a **matrix over `scripts/ci/triton_route_passing.txt`**, one Docker container per test — so adding a test file gates PRs only once it is in that allowlist. Regenerate the allowlist with `python scripts/ci/triton_route_sweep.py --all --update-allowlist` and mirror it into the workflow. -`.github/workflows/pytorchsim_triton_backend.yml` runs when the compiler pin itself moves: the compiler's own smoke kernels end to end, plus the full coverage sweep (allowlist *and* the rest, reported not gated). Both workflows need `secrets.TNPU_TOKEN` — `PSAL-POSTECH/PyTorchSim-Triton-Backend` is private. See `PyTorchSimFrontend/triton_backend/README.md`. +`.github/workflows/pytorchsim_triton_backend.yml` runs when the compiler pin itself moves: the compiler's own smoke kernels end to end, plus the full coverage sweep (allowlist *and* the rest, reported not gated). Both workflows need `secrets.TNPU_TOKEN` — `PSAL-POSTECH/PyTorchSim-Triton-Backend` is private. **For fast iteration** (skip functional check): ```bash diff --git a/PyTorchSimDevice/csrc/aten/native/Extra.cpp b/PyTorchSimDevice/csrc/aten/native/Extra.cpp index eb76f5d7b..adfc97e6a 100644 --- a/PyTorchSimDevice/csrc/aten/native/Extra.cpp +++ b/PyTorchSimDevice/csrc/aten/native/Extra.cpp @@ -27,30 +27,6 @@ int64_t _fused_sdp_choice( return static_cast(sdp::SDPBackend::error); } - // q: (B, Hq, L, E) k/v: (B, H, S, E) - const int64_t Hq = query.size(-3); - const int64_t H = key.size(-3); - const int64_t L = query.size(-2); // query sequence length - const int64_t S = key.size(-2); // key/value sequence length - - // Conditions required by the MLIR FlashSDPA kernel: - // Prefill only : L == S (decode has L == 1, not supported) - // Non-GQA : Hq == H (equal query and KV heads) - // No dropout : template has no dropout implementation - // Dense tensors : no nested tensor support - const bool can_use_mlir_flash = - (L == S) && - (Hq == H) && !enable_gqa && - sdp::check_for_dropout(params, /*debug=*/false) && - sdp::check_nested_tensor(params, /*debug=*/false); - - const bool ctx_flash = at::globalContext().userEnabledFlashSDP(); - const bool ctx_math = at::globalContext().userEnabledMathSDP(); - - if (ctx_flash && can_use_mlir_flash) { - return static_cast(sdp::SDPBackend::overrideable); - } - return static_cast(sdp::SDPBackend::math); } diff --git a/PyTorchSimDevice/torch_openreg/__init__.py b/PyTorchSimDevice/torch_openreg/__init__.py index 82f7abaa5..2e23c7e41 100644 --- a/PyTorchSimDevice/torch_openreg/__init__.py +++ b/PyTorchSimDevice/torch_openreg/__init__.py @@ -30,7 +30,7 @@ # The `npu` codegen route: Inductor's own Triton codegen, lowered by the # compiler passes. Registered here because Inductor registers a backend per -# device, once. See PyTorchSimFrontend/triton_backend/README.md. +# device, once. from PyTorchSimFrontend.triton_backend import ( TritonNPUScheduling, TritonNPUWrapperCodegen) torch._inductor.codegen.common.register_backend_for_device( diff --git a/PyTorchSimFrontend/extension_config.py b/PyTorchSimFrontend/extension_config.py index 82866161b..114ce3983 100644 --- a/PyTorchSimFrontend/extension_config.py +++ b/PyTorchSimFrontend/extension_config.py @@ -17,9 +17,7 @@ "script_systolic.py")) CONFIG_VCIX_MODEL = os.environ.get("TORCHSIM_COMPILE_VCIX_MODEL", default=os.path.join( os.environ.get("TORCHSIM_PREFIX", "/workspace"), "vcix-build", "libtpu.so")) -# the compiler runs in its own process. Both sides now hold the same LLVM 23 bindings, -# so the seam is a process boundary rather than a version one; `mlir` is a -# namespace package, and each side still selects its own root explicitly. +# the compiler runs in its own process, under this interpreter unless overridden. CONFIG_TORCHSIM_COMPILE_PYTHON = os.environ.get("TORCHSIM_COMPILE_PYTHON", default=sys.executable) diff --git a/PyTorchSimFrontend/triton_backend/compiler_bridge.py b/PyTorchSimFrontend/triton_backend/compiler_bridge.py index 3eeacf183..5b637f8b8 100644 --- a/PyTorchSimFrontend/triton_backend/compiler_bridge.py +++ b/PyTorchSimFrontend/triton_backend/compiler_bridge.py @@ -1,8 +1,6 @@ -"""Run pytorchsim-triton-compiler, out of process. +"""Run pytorchsim-triton-compiler in its own process and read the kernel object it leaves. -the compiler's passes run on LLVM 23's MLIR python bindings and this process holds LLVM -20's. `mlir` is a NAMESPACE package, so two LLVMs in one interpreter merge -silently; the seam between them is a file, which is measured to work. +The seam is kernel.json in the kernel's workdir; nothing here imports the compiler. """ import json diff --git a/Simulator/simulator.py b/Simulator/simulator.py index b92aaebc9..9aa27f741 100644 --- a/Simulator/simulator.py +++ b/Simulator/simulator.py @@ -125,8 +125,7 @@ def _send_command(self, command_type, device_index, stream_index, tog_path="", a device_index: Device index stream_index: Stream index tog_path: kernel-dir handle; TOGSim derives trace.so/trace_cycles.tsv from - its directory (the ONNX file itself is only read on the STONNE sparse - path) - empty for DEVICE_SYNC + its directory - empty for DEVICE_SYNC attribute_path: Path to attribute file - empty for DEVICE_SYNC timestamp: Timestamp in nanoseconds (default: 0) @@ -220,7 +219,6 @@ def launch_kernel(self, device_index, stream_index, tog_path, attribute_path, ti device_index: Device index stream_index: Stream index tog_path: kernel-dir handle; TOGSim derives trace.so from its directory - (the ONNX file itself is only read on the STONNE sparse path) attribute_path: Path to attribute file timestamp: Timestamp in nanoseconds (default: 0) @@ -286,7 +284,7 @@ def run_standalone( Args: model_path: kernel-dir handle; trace.so/trace_cycles.tsv are derived from - its directory (the ONNX file itself is only read on the STONNE sparse path) + its directory attribute_path: Path to attribute file autotune_mode: If True, run in autotune mode (silent) config_path: Path to TOGSim config file (required) @@ -323,16 +321,12 @@ def run_standalone( os.fsync(trace_file.fileno()) try: - # Drive the simulation from the emitted trace.so (the C++ TOG path). The - # ONNX --models_list path remains only for callers without a trace.so (the - # STONNE sparse path); the normal compile always emits one. trace_so = os.path.join(os.path.dirname(str(model_path)), "trace.so") cycle_tsv = os.path.join(os.path.dirname(str(model_path)), "trace_cycles.tsv") + if not os.path.exists(trace_so): + raise FileNotFoundError(f"{trace_so} not found -- the kernel has no trace to simulate") base_cmd = TOGSimulator.get_togsim_command(config_path, togsim_path) - if os.path.exists(trace_so): - cmd = f"{base_cmd} --trace_so {trace_so} --cycle_table {cycle_tsv}" - else: # ONNX TOG path (STONNE sparse) - cmd = f"{base_cmd} --models_list {trace_file_path}" + cmd = f"{base_cmd} --trace_so {trace_so} --cycle_table {cycle_tsv}" if extension_config.CONFIG_TOGSIM_DEBUG_LEVEL: cmd += f" --log_level {extension_config.CONFIG_TOGSIM_DEBUG_LEVEL}" diff --git a/TOGSim/CMakeLists.txt b/TOGSim/CMakeLists.txt index 0d36d4635..31d10fc5d 100644 --- a/TOGSim/CMakeLists.txt +++ b/TOGSim/CMakeLists.txt @@ -13,7 +13,6 @@ list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/extern) # C++ setttings set(CMAKE_CXX_STANDARD 17) -set(ONNX_ML 1) set(JSON_BuildTests OFF CACHE INTERNAL "") set(EXECUTABLE_OUTPUT_PATH "${CMAKE_SOURCE_DIR}/build/bin") set(LIBRARY_OUTPUT_PATH "${CMAKE_SOURCE_DIR}/build/lib") @@ -35,24 +34,7 @@ include_directories("${PROJECT_SOURCE_DIR}/extern/ramulator2/resources/wrappers" # Add libaray booksim add_subdirectory("${PROJECT_SOURCE_DIR}/extern/booksim") -# Add libary protobuf -add_subdirectory("${PROJECT_SOURCE_DIR}/extern/protobuf/cmake" EXCLUDE_FROM_ALL) -set_target_properties(libprotoc PROPERTIES FOLDER "external/protobuf") -set_target_properties(protoc PROPERTIES FOLDER "external/protobuf") - -# Add libaray stonne core -add_subdirectory("${PROJECT_SOURCE_DIR}/extern/stonneCore") - -# Add libaray onnx -add_definitions("-DONNX_NAMESPACE=onnx") -add_subdirectory("${PROJECT_SOURCE_DIR}/extern/onnx" EXCLUDE_FROM_ALL) -set_target_properties(onnx PROPERTIES FOLDER "extern/onnx") -set_target_properties(onnx_proto PROPERTIES FOLDER "extern/onnx") - -target_include_directories(Simulator PUBLIC ${PROJECT_SOURCE_DIR}/extern/stonneCore/include) target_include_directories(Simulator PUBLIC ${PROJECT_SOURCE_DIR}/include) target_include_directories(Simulator PUBLIC ${PROJECT_SOURCE_DIR}/include/scheduler) target_include_directories(Simulator PUBLIC ${PROJECT_SOURCE_DIR}/src) -target_include_directories(Simulator PUBLIC ${ONNX_INCLUDE_DIRS}) -target_link_libraries(Simulator booksim2 ramulator sstStonne) -target_link_libraries(Simulator ${PROTOBUF_LIB} onnx_proto sstStonne ${CONAN_LIBS} stdc++fs) +target_link_libraries(Simulator booksim2 ramulator ${CONAN_LIBS} stdc++fs) diff --git a/TOGSim/extern/onnx b/TOGSim/extern/onnx deleted file mode 160000 index f7ee1ac60..000000000 --- a/TOGSim/extern/onnx +++ /dev/null @@ -1 +0,0 @@ -Subproject commit f7ee1ac60d06abe8e26c9b6bbe1e3db5286b614b diff --git a/TOGSim/extern/protobuf b/TOGSim/extern/protobuf deleted file mode 160000 index 0dab03ba7..000000000 --- a/TOGSim/extern/protobuf +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 0dab03ba7bc438d7ba3eac2b2c1eb39ed520f928 diff --git a/TOGSim/extern/stonneCore b/TOGSim/extern/stonneCore deleted file mode 160000 index 97804185f..000000000 --- a/TOGSim/extern/stonneCore +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 97804185f00e98e56f74638e4282b9aecab8cfce diff --git a/TOGSim/include/DMA.h b/TOGSim/include/DMA.h index 08bdcab40..55fd02ba8 100644 --- a/TOGSim/include/DMA.h +++ b/TOGSim/include/DMA.h @@ -39,13 +39,6 @@ class DMA { tag_table[subgraph_id][key] = 1; } - void set_tag_sparse(int subgraph_id, std::vector& key) { - if (tag_table.find(subgraph_id) == tag_table.end()) { - throw std::runtime_error("Subgraph does not exist in tag_table"); - } - tag_table[subgraph_id][key] = -1; - } - void mark_tag_used(int subgraph_id, std::vector& key) { if (tag_table.find(subgraph_id) == tag_table.end()) { throw std::runtime_error("Subgraph does not exist in tag_table"); diff --git a/TOGSim/include/Instruction.h b/TOGSim/include/Instruction.h index d58a3d4bf..860c8ea7a 100644 --- a/TOGSim/include/Instruction.h +++ b/TOGSim/include/Instruction.h @@ -144,8 +144,6 @@ class Instruction : public std::enable_shared_from_this { if (_wait_keys.empty()) _wait_keys.push_back(_tag_key); return _wait_keys; } - bool is_sparse_inst() { return _is_sparse_inst; } - void set_sparse_state(bool state) { _is_sparse_inst = state; } uint64_t get_global_inst_id() const { return _global_inst_id; } // SRAM-capacity model (sec 10.4), filled by the bridge and enforced by Core: a @@ -212,7 +210,6 @@ class Instruction : public std::enable_shared_from_this { int _nr_inner_loop = 0; bool _is_async_dma=false; bool _is_indirect_mode=false; - bool _is_sparse_inst=false; std::string _indirect_index_path=""; // SRAM-capacity model (see the setters above). int64_t _sram_alloc_id = -1; diff --git a/TOGSim/include/SimulationConfig.h b/TOGSim/include/SimulationConfig.h index c099d057c..8983d7734 100644 --- a/TOGSim/include/SimulationConfig.h +++ b/TOGSim/include/SimulationConfig.h @@ -6,7 +6,7 @@ #include #include -enum class CoreType { WS_MESH, STONNE }; +enum class CoreType { WS_MESH }; enum class DramType { SIMPLE, RAMULATOR2 }; @@ -20,16 +20,13 @@ struct SimulationConfig { /* Core config */ std::vector core_type; - std::string stonne_config_path; uint32_t num_cores; uint32_t core_freq_mhz; uint32_t core_print_interval = 0; uint32_t num_systolic_array_per_core = 1; - uint32_t num_stonne_per_core = 1; - uint32_t num_stonne_port = 1; // Per-core VMEM/spad capacity (KB) for the trace-path DMA throttle (sec 10.4): a // load that would overflow the spad waits for a consumer to free a tile. 0 = unset - // -> disabled. Legacy TileGraphParser insts have alloc id -1 and are never gated. + // -> disabled. uint32_t core_spad_size_kb = 0; // SA weight-buffer depth (sec 10.4): weight tiles a systolic array holds; a // preload stalls until a slot frees (its matmuls finished). 2 = weight diff --git a/TOGSim/include/Simulator.h b/TOGSim/include/Simulator.h index c0616b89e..e41d98536 100644 --- a/TOGSim/include/Simulator.h +++ b/TOGSim/include/Simulator.h @@ -6,7 +6,6 @@ #include #include "Common.h" #include "Core.h" -#include "SparseCore.h" #include "Dram.h" #include "Interconnect.h" #include "scheduler/Scheduler.h" diff --git a/TOGSim/include/SparseCore.h b/TOGSim/include/SparseCore.h deleted file mode 100644 index a91004edf..000000000 --- a/TOGSim/include/SparseCore.h +++ /dev/null @@ -1,93 +0,0 @@ -#include -#include -#include -#include "Core.h" -#include "sstStonne.h" -#include "SimpleMem.h" -#include "Config.h" - -class TraceNode { -private: - int node_id; - int node_type; - std::string node_name; - std::set address_set; - int compute_cycle; - -public: - enum TraceType {StonneTraceCompute=6, StonneTraceLoad=7, StonneTraceStore=8}; - TraceNode(int id, std::string name, int type, int cycle = 0) - : node_id(id), node_name(name), node_type(type), compute_cycle(cycle) {} - void setAddress(std::set addr_set) { address_set = addr_set; } - friend std::ostream& operator<<(std::ostream& os, const TraceNode& node) { - os << " " << node.node_id << ": {\n" - << " \"node_id\": " << node.node_id << ",\n" - << " \"node_name\": " << std::quoted(node.node_name) << ",\n" - << " \"node_type\": " << node.node_type << ",\n" - << " \"parents\": [0],\n" - << " \"trace_address\": ["; - - bool first = true; - for (uint64_t addr : node.address_set) { - if (!first) - os << ", "; - os << addr; - first = false; - } - - os << "],\n" - << " \"trace_compute_cycle\": " << node.compute_cycle << "\n" - << " }"; - return os; - } -}; - -class SparseCore : public Core { -public: - SparseCore(uint32_t id, SimulationConfig config); - ~SparseCore(); - bool running() override; - bool can_issue(const std::shared_ptr& op) override; - void issue(std::shared_ptr tile) override; - void cycle() override; - void subCoreCycle(uint32_t subcore_id); - void stonneCycle(SST_STONNE::sstStonne *&stonneCore, uint32_t stonne_core_id, bool &retFlag); - bool has_memory_request(); - void pop_memory_request(); - mem_fetch* top_memory_request() { return _request_queue.front(); } - void push_memory_response(mem_fetch* response) override; - void print_stats() override; - void print_current_stats() override; - std::shared_ptr pop_finished_tile() override; - void finish_instruction(std::shared_ptr& inst, - InstFinishTraceTag tag = InstFinishTraceTag::Fnshed) override; - void dumpTrace(int stonne_core_id, const std::string& path); - bool isTraceMode(int stonne_core_id) { return traceMode.at(stonne_core_id); } - void setTraceMode(int stonne_core_id, bool mode) { traceMode.at(stonne_core_id) = mode; } - void checkStatus(uint32_t subcore_id); - void registerMemfetch(const std::tuple& key, std::function callback); - int allocTrafficID() { int id = traffic_id; traffic_id++; return 0; } - uint32_t num_ms = 1; - uint32_t r_port_nr = 1; - uint32_t w_port_nr = 1; - uint32_t nr_cores = 1; -private: - uint32_t rr_idx = 0; - std::vector coreBusy; - std::vector traceCoreStatus; - std::vector traceCoreCycle; - std::vector traceMode; - std::vector> traceNodeList; - std::vector> traceLoadTraffic; // To trace dma traffic - std::vector> traceStoreTraffic; // To trace dma traffic - std::vector>> percore_tiles; - std::vector stonneCores; - /* Interconnect queue */ - std::queue _request_queue; - std::queue _response_queue; - std::map, mem_fetch*> request_merge_table; - std::vector percore_stat; - std::vector percore_total_stat; - int traffic_id=0; -}; - diff --git a/TOGSim/include/Tile.h b/TOGSim/include/Tile.h index 3ba97cbd3..ffb655e3e 100644 --- a/TOGSim/include/Tile.h +++ b/TOGSim/include/Tile.h @@ -67,8 +67,6 @@ class Tile : public std::enable_shared_from_this { bool all_insts_finshed() { return _nr_insts == _nr_finished_insts; } void* get_custom_data() { return _custom_data; } void set_custom_data(void* custom_data ) { _custom_data = custom_data; } - void set_stonne_tile(bool stonne_tile) { _stonne_tile = stonne_tile; } - bool is_stonne_tile() { return _stonne_tile; } protected: std::shared_ptr _onwer_graph; @@ -88,7 +86,6 @@ class Tile : public std::enable_shared_from_this { int _scan_weight_free = 0; std::vector> _child_tiles; void *_custom_data=NULL; - bool _stonne_tile=false; }; #endif \ No newline at end of file diff --git a/TOGSim/include/TileGraph.h b/TOGSim/include/TileGraph.h index 1df9460ef..99e869b5e 100644 --- a/TOGSim/include/TileGraph.h +++ b/TOGSim/include/TileGraph.h @@ -84,7 +84,6 @@ class TileGraph { void init_cache_plan(IntervalTree::interval_vector it) { _cache_plan = std::make_shared>(std::move(it)); } - bool StonneGraph = false; class Iterator { public: diff --git a/TOGSim/include/TileGraphParser.h b/TOGSim/include/TileGraphParser.h deleted file mode 100644 index d255a7355..000000000 --- a/TOGSim/include/TileGraphParser.h +++ /dev/null @@ -1,399 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include -#include -#include "TileGraph.h" -#include "Instruction.h" -#include "sstStonne.h" -#include "IntervalTree.h" -#include "Common.h" -#include "onnx/defs/schema.h" -#include "onnx/onnx-operators_pb.h" -#include "onnx/onnx_pb.h" - -enum class TileType{ - LOOP_INDEX_NODE, - LOOP_END_NODE, - LOAD_NODE, - STORE_NODE, - COMPUTE_NODE, - MEMORY_WAIT_NODE, - STONNE_NODE, - STONNE_TRACE_COMPUTE_NODE, - STONNE_TRACE_LOAD_NODE, - STONNE_TRACE_STORE_NODE -}; - -enum class LoopType { - NORMAL_LOOP, - PARALLEL_LOOP, - ACCUMULATION_LOOP, - INNER_LOOP -}; - -class TileNode { - public: - TileNode(onnx::NodeProto& node); - static TileType get_tile_type(std::string type); - void add_child(std::shared_ptr child) { _child.push_back(std::move(child)); } - std::vector>& get_child() { return _child; } - void add_parent(std::shared_ptr parent) { _parent.push_back(std::move(parent)); } - std::vector>& get_parent() { return _parent; } - std::vector& get_child_name() { return _child_name; } - std::vector& get_parent_name() { return _parent_name; } - TileType get_type() { return _type; } - std::shared_ptr get_owner_loop() { return _owner_loop; } - std::string get_name() { return _name; } - void set_owner_loop(std::shared_ptr owner) { _owner_loop=std::move(owner); } - virtual void print_node(); - void set_depth(int depth) { _depth=depth; } - int get_depth() { return _depth; } - - private: - std::vector> _parent; - std::vector> _child; - std::vector _parent_name; - std::vector _child_name; - std::shared_ptr _owner_loop; - std::string _name; - int _depth; - TileType _type; -}; - -class TileGraphParser { - public: - TileGraphParser(std::string onnx_path, std::string attribute_path, const YAML::Node& config_yaml); - std::shared_ptr get_top_loop(); - std::unique_ptr& get_tile_graph() { return _tile_graph; } - addr_type lookup(std::string key); - void register_loop(std::shared_ptr); - void increase_loop_top() { _loop_stack_pointer++; } - void decrease_loop_top() { _loop_stack_pointer--; } - int get_loop_size(std::string key) { return std::get<0>(_loop_size_map[key]); } - int get_loop_step(std::string key) { return std::get<1>(_loop_size_map[key]); } - LoopType get_loop_type(std::string key) { return std::get<2>(_loop_size_map[key]); } - const std::map> & get_loop_map() { return _loop_size_map; } - const std::vector &lookupNumaInfo(std::string key); - int getCoreIdFromConfig(const YAML::Node& attribute_config, int subgraph_id); - std::string getMetaByName(std::string key) { return _tog_meta[key]; } - const YAML::Node& get_attribute_file() { return _attribute_config; } - std::vector calc_tag(std::vector& accum_tag, std::vector& tag_idx, std::vector& tag_stride); - void register_memory_tag(std::string name, std::vector& tag_key); - bool check_memory_tag(std::string name, std::vector& tag_key); - void clear_tag_table() { _tag_table.clear(); } - std::string get_indirect_path() { - namespace fs = std::filesystem; - fs::path original(_attribute_path); - fs::path base_folder = original.parent_path().parent_path(); - fs::path new_path = base_folder / "indirect_access" / (std::string("indirect_index") + std::to_string(indirect_counter) + ".raw"); - return new_path.string(); - } - std::string get_sparse_tile_meta_path() { - namespace fs = std::filesystem; - fs::path original(_attribute_path); - fs::path base_folder = original.parent_path().parent_path(); - fs::path new_path = base_folder / "dma_access" / (std::string("sparse_tile.raw")); - return new_path.string(); - } - void load_sparse_meta_data() { - /* Prepare runtime attribute */ - std::string sparse_meta_path = get_sparse_tile_meta_path(); - std::ifstream file(sparse_meta_path, std::ios::binary); - if (file) { - file.seekg(0, std::ios::end); - std::streamsize size = file.tellg(); - file.seekg(0, std::ios::beg); - size_t count = size / sizeof(int64_t); - for (size_t i = 0; i < count; ++i) { - int64_t val; - file.read(reinterpret_cast(&val), sizeof(int64_t)); - sparse_tile_set.insert(val); - } - } - } - void inc_indirect_counter() { indirect_counter++; } - uint64_t get_dma_counter() { return dma_counter; } - void inc_dma_counter() { dma_counter++; } - bool is_sparse_tile(uint64_t idx) { return sparse_tile_set.find(idx) != sparse_tile_set.end(); } - int64_t register_addr_name(const std::string& addr_name) { - if (_addr_name_map.find(addr_name) == _addr_name_map.end()) - _addr_name_map[addr_name] = static_cast(_addr_name_map.size()); - return _addr_name_map[addr_name]; - } - int64_t get_addr_name_id(const std::string& addr_name) { return _addr_name_map[addr_name]; } - - private: - void register_tile(std::shared_ptr tile_node); - void _tile_generate() {} - void _base_addr_update() {} - void _tile_index_generate() {} - int _loop_stack_pointer = 0; - - YAML::Node _attribute_config; - YAML::Node _config_yaml; - std::string _tog_path; - std::string _attribute_path; - uint64_t indirect_counter = 0; - uint64_t dma_counter = 0; - std::set sparse_tile_set; - std::map> _output_map; - std::vector>> _loop_nodes; - std::vector> _tile_vec; - std::unique_ptr _tile_graph; - std::map _arg_to_address; - std::map> _arg_numa_stride; - std::vector> _cache_plan; - std::map> _loop_size_map; - std::map _tog_meta; - std::map>, uint32_t> _tag_table; - std::unordered_map _addr_name_map; -}; - -class TileComputeNode : public TileNode { - public: - TileComputeNode(onnx::NodeProto& node); - uint32_t get_cycle() { return _cycle; } - uint32_t get_overlapping_cycle() { return _overlapping_cycle; } - int get_compute_type() { return _compute_type; } - void print_node(); - - private: - std::map> tile_map; - uint32_t _cycle; - uint32_t _overlapping_cycle = 0; - int _compute_type; -}; - -class TileMemoryNode : public TileNode { - public: - TileMemoryNode(onnx::NodeProto& node); - std::string get_base_addr_name() { return _base_addr_name; } - size_t get_elem_bits() const { return _elem_bits; } - std::vector get_tile_size() { return _tile_size; } - std::vector& get_tile_stride() { return _tile_stride; } - std::vector& get_tag_idx_list() { return _tag_idx_list; } - std::vector& get_tag_stride_list() { return _tag_stride_list; } - std::vector& get_loop_idx_list() { return _loop_idx_list; } - std::vector& get_loop_stride_list () { return _loop_stride_list; } - bool is_async_node() { return _is_async; } - bool is_indirect() { return _is_indirect; } - void print_node() override; - - private: - std::vector _tile_size; - std::vector _tile_stride; - size_t _elem_bits = 0; - bool _is_async; - bool _is_indirect; - std::string _base_addr_name; - std::vector _tag_idx_list; - std::vector _tag_stride_list; - std::vector _loop_idx_list; - std::vector _loop_stride_list; -}; - -class TileMemoryWaitNode : public TileNode { - public: - TileMemoryWaitNode(onnx::NodeProto& node); - std::string get_base_addr_name() { return _base_addr_name; } - std::vector& get_tag_idx_list() { return _tag_idx_list; } - std::vector& get_tag_stride_list() { return _tag_stride_list; } - std::vector& get_tag_divider_list() { return _tag_divider_list; } - void print_node() override; - - private: - std::vector _tag_idx_list; - std::vector _tag_stride_list; - std::vector _tag_divider_list; - std::string _base_addr_name; -}; - -class TileLoopNode : public TileNode { - public: - TileLoopNode(onnx::NodeProto& node); - void add_body(std::shared_ptr body) { _body_node.push_back(body); } - std::vector> get_tiles_from_iter(TileGraphParser*, std::map&); - std::string get_idx_name() { return _tile_index_name; } - uint64_t get_start() { return _start; } - uint64_t get_stride() { return _stride; } - uint64_t get_end() { return _end; } - LoopType get_loop_type() { return _loop_type; } - void print_node() override; - private: - std::string _tile_index_name; - uint64_t _stride; - uint64_t _start; - uint64_t _end; - LoopType _loop_type; - std::vector> _body_node; -}; - -class TileLoopEndNode : public TileNode { - public: - TileLoopEndNode(onnx::NodeProto& node) : TileNode(node) {} -}; - -class TileStonneNode : public TileNode { - public: - TileStonneNode(onnx::NodeProto& node) : TileNode(node) { - for (auto attribute : node.attribute()) { - if (attribute.name() == "torchsim_stonne_operation") { - std::string op_type = attribute.s(); - if (op_type == "CONV") { - desc.operation = Layer_t::CONV; - } else if (op_type == "GEMM") { - desc.operation = Layer_t::GEMM; - } else if (op_type == "POOL") { - desc.operation = Layer_t::POOL; - } else if (op_type == "FC") { - desc.operation = Layer_t::FC; - } else if (op_type == "SPARSE_DENSE") { - desc.operation = Layer_t::SPARSE_DENSE; - } else if (op_type == "bitmapSpMSpM") { - desc.operation = Layer_t::bitmapSpMSpM; - } else if (op_type == "csrSpMM") { - desc.operation = Layer_t::csrSpMM; - } else if (op_type == "outerProductGEMM") { - desc.operation = Layer_t::outerProductGEMM; - } else if (op_type == "gustavsonsGEMM") { - desc.operation = Layer_t::gustavsonsGEMM; - } else { - spdlog::error("[TileStonneNode] Unknown operation type: {}", op_type); - throw std::runtime_error("Invalid operation type in TileStonneNode"); - } - } else if (attribute.name() == "torchsim_stonne_layer_name") { - desc.layer_name = attribute.s(); - } else if (attribute.name() == "torchsim_stonne_mem_init") { - desc.mem_init = attribute.s(); - } else if (attribute.name() == "torchsim_stonne_R") { - desc.R = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_S") { - desc.S = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_C") { - desc.C = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_K") { - desc.K = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_G") { - desc.G = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_N") { - desc.N = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_X") { - desc.X = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_Y") { - desc.Y = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_X_") { - desc.X_ = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_Y_") { - desc.Y_ = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_strides") { - desc.strides = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_T_R") { - desc.T_R = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_T_S") { - desc.T_S = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_T_C") { - desc.T_C = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_T_K") { - desc.T_K = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_T_G") { - desc.T_G = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_T_N") { - desc.T_N = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_T_X_") { - desc.T_X_ = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_T_Y_") { - desc.T_Y_ = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_GEMM_K") { - desc.GEMM_K = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_GEMM_N") { - desc.GEMM_N = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_GEMM_M") { - desc.GEMM_M = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_GEMM_T_K") { - desc.GEMM_T_K = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_GEMM_T_N") { - desc.GEMM_T_N = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_GEMM_T_M") { - desc.GEMM_T_M = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_matrix_a_dram_address") { - desc.matrix_a_dram_address = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_matrix_b_dram_address") { - desc.matrix_b_dram_address = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_matrix_c_dram_address") { - desc.matrix_c_dram_address = attribute.i(); - } else if (attribute.name() == "torchsim_stonne_mem_matrix_c_file_name") { - desc.mem_matrix_c_file_name = attribute.s(); - } else if (attribute.name() == "torchsim_stonne_bitmap_matrix_a_init") { - desc.bitmap_matrix_a_init = attribute.s(); - } else if (attribute.name() == "torchsim_stonne_bitmap_matrix_b_init") { - desc.bitmap_matrix_b_init = attribute.s(); - } else if (attribute.name() == "torchsim_stonne_rowpointer_matrix_a_init") { - desc.rowpointer_matrix_a_init = attribute.s(); - } else if (attribute.name() == "torchsim_stonne_colpointer_matrix_a_init") { - desc.colpointer_matrix_a_init = attribute.s(); - } else if (attribute.name() == "torchsim_stonne_rowpointer_matrix_b_init") { - desc.rowpointer_matrix_b_init = attribute.s(); - } else if (attribute.name() == "torchsim_stonne_colpointer_matrix_b_init") { - desc.colpointer_matrix_b_init = attribute.s(); - } else if (attribute.name() == "torchsim_bitmap_matrix_a_init") { - desc.bitmap_matrix_a_init = attribute.s(); - } else if (attribute.name() == "torchsim_bitmap_matrix_b_init") { - desc.bitmap_matrix_b_init = attribute.s(); - } else if (attribute.name() == "torchsim_mem_matrix_c_file_name") { - desc.mem_matrix_c_file_name = attribute.s(); - } else if (attribute.name() == "torchsim_trace_path") { - desc.trace_path = attribute.s(); - } else { - spdlog::warn("[TileStonneNode] Unrecognized attribute: {}", attribute.name()); - } - } - } - SST_STONNE::StonneOpDesc* getDesc() { return &desc; } - void print_node() override; - private: - SST_STONNE::StonneOpDesc desc; -}; - -class TileStonneTraceComputeNode : public TileNode { - public: - TileStonneTraceComputeNode(onnx::NodeProto& node) : TileNode(node) { - for (auto attribute : node.attribute()) { - if (attribute.name() == "torchsim_trace_compute_cycle") { - _cycle = attribute.i(); - } - } - } - uint32_t get_cycle() { return _cycle; } - void print_node(); - - private: - uint64_t _cycle; -}; - -class TileStonneTraceMemoryNode : public TileNode { - public: - TileStonneTraceMemoryNode(onnx::NodeProto& node) : TileNode(node) { - for (auto attribute : node.attribute()) { - if (attribute.name() == "torchsim_trace_address") { - trace_address.assign(attribute.ints().begin(), attribute.ints().end()); - } - } - } - std::vector& get_address() { return trace_address; } - void print_node(); - - private: - std::vector trace_address; -}; -class TileStonneTraceLoadNode : public TileStonneTraceMemoryNode { - public: - using TileStonneTraceMemoryNode::TileStonneTraceMemoryNode; -}; - -class TileStonneTraceStoreNode : public TileStonneTraceMemoryNode { - public: - using TileStonneTraceMemoryNode::TileStonneTraceMemoryNode; -}; \ No newline at end of file diff --git a/TOGSim/src/Common.cc b/TOGSim/src/Common.cc index 6f9a74d78..9346ed117 100644 --- a/TOGSim/src/Common.cc +++ b/TOGSim/src/Common.cc @@ -49,8 +49,6 @@ SimulationConfig initialize_config(const YAML::Node& config, for (const auto& core_type : core_types) { if (core_type == "ws_mesh") { parsed_config.core_type.push_back(CoreType::WS_MESH); - } else if (core_type == "stonne") { - parsed_config.core_type.push_back(CoreType::STONNE); } else { throw std::runtime_error(fmt::format("Not implemented core type: {}", core_type)); } @@ -68,16 +66,8 @@ SimulationConfig initialize_config(const YAML::Node& config, parsed_config.core_spad_size_kb = config["core_spad_size_kb"].as(); if (config["sa_weight_buffer_depth"]) parsed_config.sa_weight_buffer_depth = config["sa_weight_buffer_depth"].as(); - if (config["num_stonne_per_core"]) - parsed_config.num_stonne_per_core = config["num_stonne_per_core"].as(); - if (config["num_stonne_port"]) - parsed_config.num_stonne_port = config["num_stonne_port"].as(); parsed_config.core_print_interval = get_config_value(config, "core_stats_print_period_cycles"); - /* Stonne config */ - if (config["stonne_config_path"]) - parsed_config.stonne_config_path = config["stonne_config_path"].as(); - /* DRAM config */ std::string dram_type_str = get_config_value(config, "dram_type"); diff --git a/TOGSim/src/Core.cc b/TOGSim/src/Core.cc index de0a0574d..c5494f008 100644 --- a/TOGSim/src/Core.cc +++ b/TOGSim/src/Core.cc @@ -101,7 +101,7 @@ bool Core::can_issue(const std::shared_ptr& op) { * (unknown) falls back to 2. */ size_t M = op->get_spad_footprint(); int max_concurrent = (_sram_capacity && M > _sram_capacity / 2) ? 1 : 2; - return (int)_tiles.size() < max_concurrent && !op->is_stonne_tile(); + return (int)_tiles.size() < max_concurrent; } void Core::issue(std::shared_ptr op) { @@ -331,14 +331,7 @@ void Core::cycle() { { /* Check another MOVIN with same tag is issued */ auto& key = inst->get_tag_id(); - if (inst->is_sparse_inst()) { - _dma.register_tag(inst->subgraph_id, key); - _dma.set_tag_sparse(inst->subgraph_id, key); - finish_instruction(inst); - issued = true; - _stat_tot_skipped_inst.at(static_cast(inst->get_opcode()))++; - break; - } else if (inst->is_async_dma() && _dma.tag_key_exist(inst->subgraph_id, key)) { + if (inst->is_async_dma() && _dma.tag_key_exist(inst->subgraph_id, key)) { bool finished = _dma.get_tag_finish(inst->subgraph_id, key); if (finished) finish_instruction(inst); diff --git a/TOGSim/src/Simulator.cc b/TOGSim/src/Simulator.cc index 86a6109f0..30c304e87 100644 --- a/TOGSim/src/Simulator.cc +++ b/TOGSim/src/Simulator.cc @@ -32,9 +32,6 @@ Simulator::Simulator(SimulationConfig config, YAML::Node hardware_config_yaml) spdlog::info("[Config/Core] Core {}: core_freq_mhz: {}, systolic_arrays_per_core: {}", core_index, config.core_freq_mhz, config.num_systolic_array_per_core); _cores.at(core_index) = std::make_unique(core_index, _config); - } else if(config.core_type[core_index] == CoreType::STONNE) { - spdlog::info("[Config/Core] Core {}: core_freq_mhz: {}, core_type: Stonne", core_index, config.core_freq_mhz); - _cores.at(core_index) = std::make_unique(core_index, _config); } else { throw std::runtime_error(fmt::format("Not implemented Core type {} ", (int)config.core_type[core_index])); diff --git a/TOGSim/src/SparseCore.cc b/TOGSim/src/SparseCore.cc deleted file mode 100644 index 82e597eaa..000000000 --- a/TOGSim/src/SparseCore.cc +++ /dev/null @@ -1,498 +0,0 @@ -#include "SparseCore.h" -#include "TraceLogTags.h" - -SparseCore::SparseCore(uint32_t id, SimulationConfig config) : Core(id, config) { - /* Init stonne cores*/ - nr_cores = config.num_stonne_per_core; - coreBusy.resize(nr_cores); - traceCoreStatus.resize(nr_cores); - traceCoreCycle.resize(nr_cores); - traceNodeList.resize(nr_cores); - traceLoadTraffic.resize(nr_cores); - traceStoreTraffic.resize(nr_cores); - percore_tiles.resize(nr_cores); - stonneCores.resize(nr_cores); - traceMode.resize(nr_cores); - percore_stat.resize(nr_cores); - percore_total_stat.resize(nr_cores); - for (int i=0; iinit(1); - coreBusy.at(i) = false; - traceCoreStatus.at(i) = 0; - traceCoreCycle.at(i) = 0; - percore_tiles.at(i) = std::vector>(); - percore_stat.at(i).reset(); - percore_total_stat.at(i).reset(); - } - - Config stonneConfig = stonneCores.at(0)->getStonneConfig(); - unsigned int core_freq_mhz = config.core_freq_mhz; // MHz; - num_ms = stonneConfig.m_MSNetworkCfg.ms_size; - r_port_nr = config.num_stonne_port; - w_port_nr = config.num_stonne_port; - - double compute_throughput = static_cast(num_ms) * core_freq_mhz / 1e3; // FLOPs/sec - double dn_bandwidth = static_cast(r_port_nr) * config.dram_req_size * core_freq_mhz * 1e6 / 8.0 / 1e9; // GB/s - double rn_bandwidth = static_cast(w_port_nr) * config.dram_req_size * core_freq_mhz * 1e6 / 8.0 / 1e9; // GB/s - for (int i=0; i tile) { - int32_t selected_core_idx = -1; - for (int i=0; iinit(1); - traceNodeList.at(selected_core_idx).clear(); - - SST_STONNE::StonneOpDesc *opDesc = static_cast(tile->get_custom_data()); - bool is_trace_mode = true; - if (opDesc) { - is_trace_mode = false; - stonneCores.at(selected_core_idx)->setup(*opDesc, 0x1000000 * selected_core_idx); // FIXME. To avoid same address - stonneCores.at(selected_core_idx)->init(1); - } - setTraceMode(selected_core_idx, is_trace_mode); - percore_tiles.at(selected_core_idx).push_back(tile); - coreBusy.at(selected_core_idx) = true; - spdlog::info("[{}][StonneCore {}/{}][Launch] New operation (trace_mode: {})", _core_cycle, _id, selected_core_idx, is_trace_mode); -}; - -bool SparseCore::can_issue(const std::shared_ptr& op) { - bool idle_exist = false; - for (bool flag : coreBusy) { - idle_exist |= !flag; - } - return idle_exist && op->is_stonne_tile(); -} - -void SparseCore::checkStatus(uint32_t subcore_id) { - auto& stonneCore = stonneCores.at(subcore_id); - int new_status = stonneCore->getMCFSMStats(); - int compute_cycle = stonneCore->getMSStats().n_multiplications; - if (traceCoreStatus.at(subcore_id) != new_status) { - spdlog::trace("[{}][StonneCore {}/{}][Transition] status {} -> {}, Load/Store: {}/{}, compute_cycle: {}", - _core_cycle, _id, subcore_id, traceCoreStatus.at(subcore_id), new_status, - traceLoadTraffic.at(subcore_id).size(), traceStoreTraffic.at(subcore_id).size(), (compute_cycle - traceCoreCycle.at(subcore_id))/num_ms); - if (traceLoadTraffic.at(subcore_id).size()) { - TraceNode load_node = TraceNode(traceNodeList.at(subcore_id).size()+2, "load", TraceNode::StonneTraceLoad); - load_node.setAddress(traceLoadTraffic.at(subcore_id)); - traceNodeList.at(subcore_id).push_back(load_node); - } - if (_core_cycle - traceCoreCycle.at(subcore_id)) {//((compute_cycle - traceCoreCycle.at(subcore_id))/num_ms) { - TraceNode compute_node = TraceNode(traceNodeList.at(subcore_id).size()+2, "compute", TraceNode::StonneTraceCompute, _core_cycle - traceCoreCycle.at(subcore_id)); - traceNodeList.at(subcore_id).push_back(compute_node); - } - if (traceStoreTraffic.at(subcore_id).size()) { - TraceNode store_node = TraceNode(traceNodeList.at(subcore_id).size()+2, "store", TraceNode::StonneTraceStore); - store_node.setAddress(traceStoreTraffic.at(subcore_id)); - traceNodeList.at(subcore_id).push_back(store_node); - } - - traceCoreStatus.at(subcore_id) = new_status; - traceCoreCycle.at(subcore_id) = _core_cycle; - traceLoadTraffic.at(subcore_id).clear(); - traceStoreTraffic.at(subcore_id).clear(); - } -} - -void SparseCore::subCoreCycle(uint32_t subcore_id) { - if (!traceMode.at(subcore_id)) { - auto& stonneCore = stonneCores.at(subcore_id); - stonneCore->cycle(); - - /* Check FSM status transition */ - checkStatus(subcore_id); - - /* Send Memory Request */ - while (SimpleMem::Request* req = stonneCore->popRequest()) { - uint64_t target_addr = (req->getAddress() / _config.dram_req_size) * _config.dram_req_size; - mem_access_type acc_type; - mf_type type; - - switch(req->getcmd()) { - case SimpleMem::Request::Read: - acc_type = mem_access_type::GLOBAL_ACC_R; - type = mf_type::READ_REQUEST; - traceLoadTraffic.at(subcore_id).insert(target_addr); - break; - case SimpleMem::Request::Write: - acc_type = mem_access_type::GLOBAL_ACC_W; - type = mf_type::WRITE_REQUEST; - traceStoreTraffic.at(subcore_id).insert(target_addr); - break; - default: - spdlog::error("[StonneCore] Invalid request type from core"); - return; - } - req->request_time = _core_cycle; - req->stonneId = subcore_id; - std::tuple key = std::make_tuple(target_addr, acc_type, type, allocTrafficID()); - registerMemfetch(key, [this, req, acc_type, type]() { - spdlog::trace("[{}][StonneCore][DRAM Response] Round Trip Cycle: {}, Address: {:#x}, Request Type: {}, DRAM Req Size: {}", \ - _core_cycle, _core_cycle - req->request_time, req->getAddress(), int(req->getcmd()), _config.dram_req_size); - req->setReply(); - stonneCores.at(req->stonneId)->pushResponse(req); - }); - } - - /* Finish stonne core */ - if (coreBusy.at(subcore_id) && stonneCore->isFinished()) { - stonneCore->finish(); - spdlog::info("[{}][StonneCore {}/{}][Finish] Operation done", _core_cycle, _id, subcore_id); - std::shared_ptr target_tile = percore_tiles.at(subcore_id).front(); - SST_STONNE::StonneOpDesc *opDesc = static_cast(target_tile->get_custom_data()); - if (opDesc->trace_path != "") - dumpTrace(subcore_id, opDesc->trace_path); - - target_tile->set_status(Tile::Status::FINISH); - _finished_tiles.push(target_tile); - percore_tiles.at(subcore_id).erase(percore_tiles.at(subcore_id).begin()); - coreBusy.at(subcore_id) = false; - } - } else { - /* Check finished computation */ - auto& target_pipeline = get_compute_pipeline(0); - if (!target_pipeline.empty()) { - if (target_pipeline.front()->finish_cycle <= _core_cycle) { - finish_instruction(target_pipeline.front()); - target_pipeline.pop(); - } - percore_stat.at(subcore_id).n_multiplications += num_ms; - } - - /* Check finished dma operation */ - bool retry=true; - while (retry) { - retry = false; - for (auto it=_dma_finished_queue.begin();it!=_dma_finished_queue.end();it++) { - std::shared_ptr& instruction = _dma_finished_queue.at(0); - /* Pass not finished instruction */ - if (instruction->get_waiting_request()) - continue; - - /* Finish DMA read instruction */ - if (instruction->is_dma_read()) - finish_instruction(instruction); - /* Erase the instruction in DMA finished queue */ - _dma_finished_queue.erase(_dma_finished_queue.begin()); - retry = true; - break; - } - } - - auto& tile_queue = percore_tiles.at(subcore_id); - if (tile_queue.empty()) - return; - auto& instructions = tile_queue.front()->get_instructions(); - - /* Finish stonne core */ - if (coreBusy.at(subcore_id) && instructions.empty()) { - std::shared_ptr target_tile = percore_tiles.at(subcore_id).front(); - target_tile->set_status(Tile::Status::FINISH); - _finished_tiles.push(target_tile); - percore_tiles.at(subcore_id).erase(percore_tiles.at(subcore_id).begin()); - coreBusy.at(subcore_id) = false; - return; - } - - /* Peek instruction*/ - if (instructions.empty()) - return; - auto& inst = instructions.front(); - if (!inst->is_ready()) - return; - - - bool issued = false; - switch (inst->get_opcode()) { - case Opcode::MOVIN: - { - auto acc_type = mem_access_type::GLOBAL_ACC_R; - auto type = mf_type::READ_REQUEST; - spdlog::trace("[{}][StonneCore {}/{}][{}] {}", - _core_cycle, - _id, - subcore_id, - TraceLogTag::pad15(TraceLogTag::kInstructionIssued), - opcode_to_string(inst->get_opcode())); - for (auto addr : inst->get_trace_address()) { - addr = addr - (addr & _config.dram_req_size-1); - inst->inc_waiting_request(); - std::tuple key = std::make_tuple(addr, acc_type, type, allocTrafficID()); - uint64_t current_time = _core_cycle; - registerMemfetch(key, [this, inst, addr, current_time, type]() { - spdlog::trace("[{}][StonneCore {}][RESPONSE] Round Trip Cycle: {}, Address: {:#x}, Request Type: {}, DRAM Req Size: {}", \ - this->_core_cycle, _id, this->_core_cycle - current_time, addr, int(type), _config.dram_req_size); - inst->dec_waiting_request(); - }); - } - issued = true; - _dma_finished_queue.push_back(std::move(inst)); - } - break; - case Opcode::MOVOUT: - { - auto acc_type = mem_access_type::GLOBAL_ACC_W; - auto type = mf_type::WRITE_REQUEST; - spdlog::trace("[{}][StonneCore {}/{}][{}] {}", - _core_cycle, - _id, - subcore_id, - TraceLogTag::pad15(TraceLogTag::kInstructionIssued), - opcode_to_string(inst->get_opcode())); - for (auto addr : inst->get_trace_address()) { - addr = addr - (addr & _config.dram_req_size-1); - inst->inc_waiting_request(); - std::tuple key = std::make_tuple(addr, acc_type, type, allocTrafficID()); - uint64_t current_time = _core_cycle; - registerMemfetch(key, [this, inst, addr, current_time, type]() { - spdlog::trace("[{}][StonneCore {}][RESPONSE] Round Trip Cycle: {}, Address: {:#x}, Request Type: {}, DRAM Req Size: {}", \ - this->_core_cycle, _id, this->_core_cycle - current_time, addr, int(type), _config.dram_req_size); - inst->dec_waiting_request(); - }); - } - issued = true; - finish_instruction(inst); - _dma_finished_queue.push_back(std::move(inst)); - } - break; - case Opcode::COMP: - { - auto& target_pipeline = get_compute_pipeline(0); - if (target_pipeline.empty()) - inst->finish_cycle = _core_cycle + inst->get_compute_cycle(); - else - inst->finish_cycle = target_pipeline.back()->finish_cycle + inst->get_compute_cycle(); - spdlog::trace("[{}][StonneCore {}/{}][{}] {}, finish_at={}", - _core_cycle, - _id, - subcore_id, - TraceLogTag::pad15(TraceLogTag::kInstructionIssued), - opcode_to_string(inst->get_opcode()), - inst->finish_cycle); - target_pipeline.push(inst); - issued = true; - } - break; - default: - spdlog::error("Undefined instruction opcode type"); - exit(EXIT_FAILURE); - } - if (issued) { - instructions.erase(std::find(instructions.begin(), instructions.end(), inst)); - } - } -} - -void SparseCore::cycle() { - _core_cycle++; - /* Handle core cycle*/ - for (uint32_t subcore_id=0; subcore_idget_addr(), int(req_pair.second->get_access_type()), int(req_pair.second->get_type()), - _config.dram_req_size, nr_request); - nr_request++; - break; - } - } - - // Send Memory Response - nr_request = 0; - while (!_response_queue.empty()) { - mem_fetch* resp_wrapper = _response_queue.front(); - auto* callbacks = static_cast>*>(resp_wrapper->get_custom_data()); - for (int i=0; isize(); i++) { - (*callbacks).at(i)(); - } - delete callbacks; - delete resp_wrapper; - _response_queue.pop(); - if (++nr_request > w_port_nr) - break; - } - - /* Check print stat */ - if(_config.core_print_interval && _core_cycle % _config.core_print_interval == 0) - print_current_stats(); -} - -bool SparseCore::has_memory_request() { - return !_request_queue.empty(); -} - -void SparseCore::pop_memory_request() { - _request_queue.pop(); -} - -void SparseCore::push_memory_response(mem_fetch* response) { - _response_queue.push(response); -} - -void SparseCore::print_current_stats() { - spdlog::info("========= Sparse Core stat ========="); - for (size_t i = 0; i < stonneCores.size(); ++i) { - if (!isTraceMode(i)) { - MSwitchStats stats = stonneCores.at(i)->getMSStats(); - stats -= percore_total_stat.at(i); - percore_stat.at(i) = stats; - percore_total_stat.at(i) = stonneCores.at(i)->getMSStats(); - } else { - percore_total_stat.at(i) += percore_stat.at(i); - } - cycle_type nr_mul = percore_stat.at(i).n_multiplications; - percore_stat.at(i).reset(); - spdlog::info("StonneCore [{}][{}] : nr_multiplications: {}", _id, i, nr_mul); - } - spdlog::info("StonneCore [{}] : Total cycle {}", _id, _core_cycle); -} - -void SparseCore::print_stats() { - spdlog::info("========= Sparse Core stat ========="); - for (size_t i = 0; i < stonneCores.size(); ++i) { - if (!isTraceMode(i)) { - MSwitchStats stats = stonneCores.at(i)->getMSStats(); - stats -= percore_total_stat.at(i); - percore_stat.at(i) = stats; - percore_total_stat.at(i) = stats; - } else { - percore_total_stat.at(i) += percore_stat.at(i); - } - cycle_type nr_mul = percore_total_stat.at(i).n_multiplications; - spdlog::info("StonneCore [{}][{}] : nr_multiplications: {}", _id, i, nr_mul); - } - spdlog::info("StonneCore [{}] : Total cycle {}", _id, _core_cycle); -} - -std::shared_ptr SparseCore::pop_finished_tile() { - std::shared_ptr result = std::make_unique(Tile(Tile::Status::EMPTY)); - if (_finished_tiles.size() > 0) { - result = std::move(_finished_tiles.front()); - _finished_tiles.pop(); - } - return result; -} - -void SparseCore::finish_instruction(std::shared_ptr& inst, InstFinishTraceTag tag) { - if (tag == InstFinishTraceTag::DmaRespComplete) { - if (!inst->finished) { - spdlog::error("[{}][StonneCore {}][Error] ALL_DRAM_RESPONSES_RECEIVED trace but inst not finished", - _core_cycle, - _id); - exit(EXIT_FAILURE); - } - spdlog::trace("[{}][StonneCore {}][{}][INST_ID={}] {}", - _core_cycle, - _id, - TraceLogTag::pad15(TraceLogTag::kAllDramResponsesReceived), - inst->get_global_inst_id(), - opcode_to_string(inst->get_opcode())); - return; - } - if (inst->finished) { - spdlog::error("[{}][StonneCore {}][Error] {} inst already finished!!", _core_cycle, _id, - opcode_to_string(inst->get_opcode())); - exit(EXIT_FAILURE); - } - inst->finish_instruction(); - count_unit_admitted(inst); - static_cast(inst->get_owner())->inc_finished_inst(); - const char* trace_tag = (tag == InstFinishTraceTag::DmaIssueComplete) - ? TraceLogTag::kAsyncDmaAllRequestsIssued - : TraceLogTag::kInstructionFinished; - const std::string tag15 = TraceLogTag::pad15(trace_tag); - if (inst->get_opcode() == Opcode::COMP) { - spdlog::info("[{}][StonneCore {}][{}] {}", _core_cycle, _id, tag15, - opcode_to_string(inst->get_opcode())); - } else if (inst->get_opcode() == Opcode::MOVIN || inst->get_opcode() == Opcode::MOVOUT) { - spdlog::info("[{}][StonneCore {}][{}] {}", _core_cycle, _id, tag15, - opcode_to_string(inst->get_opcode())); - } -} - -void SparseCore::registerMemfetch(const std::tuple& key, std::function callback) { - if (request_merge_table.find(key) == request_merge_table.end()) { - mem_fetch* req_wrapper = new mem_fetch(std::get<0>(key), std::get<1>(key), std::get<2>(key), _config.dram_req_size, -1); - - auto* callbacks = new std::vector>(); - req_wrapper->set_custom_data(static_cast(callbacks)); - request_merge_table[key] = req_wrapper; - } - mem_fetch* req_wrapper = request_merge_table[key]; - auto* callbacks = static_cast>*>(req_wrapper->get_custom_data()); - callbacks->push_back(callback); -} - -void SparseCore::dumpTrace(int stonne_core_id, const std::string& path) { - std::ofstream outFile(path); - if (!outFile) { - spdlog::error("[StonneCore] Failed to make trace dump file to \"{}\"", path); - return; - } - // Static nodes for the graph - outFile << "graph = {\n 0: {\n" - << " \"node_id\": 0,\n" - << " \"node_name\": \"root\",\n" - << " \"node_type\": 0,\n" - << " \"parents\": [],\n" - << " \"children\": [1]\n" - << " },\n" - << " 1: {\n" - << " \"node_id\": 1,\n" - << " \"node_name\": \"loopNode\",\n" - << " \"node_type\": 2,\n" - << " \"parents\": [0],\n" - << " \"children\": [2],\n" - << " \"loop_index\": \"loop_arg000\",\n" - << " \"loop_start\": 0,\n" - << " \"loop_end\": 1,\n" - << " \"loop_step\": 1,\n" - << " \"loop_type\": \"outer_loop\"" - << " },\n"; - - // Output traceNodeList - for (size_t i = 0; i < traceNodeList.at(stonne_core_id).size(); ++i) { - if (i != 0) outFile << ",\n"; - outFile << traceNodeList.at(stonne_core_id)[i]; - } - outFile << "\n}" << std::endl; - spdlog::info("[{}][StonneCore] Success to save trace dump file to \"{}\"", _core_cycle, path); -} diff --git a/TOGSim/src/TileGraphParser.cc b/TOGSim/src/TileGraphParser.cc deleted file mode 100644 index c252258ec..000000000 --- a/TOGSim/src/TileGraphParser.cc +++ /dev/null @@ -1,954 +0,0 @@ -#include "TileGraphParser.h" - -void printIndexMap(std::string prefix, const std::map& indexMap) { - std::ostringstream oss; - for (const auto& [key, value] : indexMap) { - oss << "{" << key << ": " << value << "} "; - } - spdlog::trace("{}: {}", prefix, oss.str()); - -} - -uint32_t calculateAddress(const std::vector& loop_size, const std::vector& loop_idx) { - std::vector stride_list(loop_size.size(), 1); - - for (int i = loop_size.size() - 2; i >= 0; --i) { - stride_list[i] = stride_list[i + 1] * loop_size[i + 1]; - } - int address = std::inner_product( - stride_list.begin(), stride_list.end(), - loop_idx.begin(), - 0 - ); - return address; -} - - -int getLoopIndexValue(const std::map& iter, const std::string& loop_idx) { - // Check if loop_idx starts with "c" - if (!loop_idx.empty() && loop_idx[0] == 'c') { - // Extract substring after 'c' and convert to integer - const char* numberPart = loop_idx.c_str() + 1; // Skip the first character 'c' - int convertedValue = std::atoi(numberPart); - return convertedValue; - } - - // If loop_idx does not start with 'c', check in the map - auto it = iter.find(loop_idx); - if (it != iter.end()) { - return it->second; - } - - // If loop_idx is not found, throw an exception - throw std::runtime_error("Key not found in map and does not start with 'c': " + loop_idx); -} - -std::vector calc_output_idx(TileGraphParser* tog_parser, std::map& iter) { - // Extract outer loop - // Extract inner loop - std::vector outer_loop; - std::vector inner_loop; - uint32_t step = std::stoi(tog_parser->getMetaByName("systolic_size")); - int offset = 0; - for (auto loop_idx = iter.begin(); loop_idx != iter.end(); ++loop_idx) { - if (tog_parser->get_loop_type(loop_idx->first)!=LoopType::INNER_LOOP) - outer_loop.push_back(loop_idx->second); - else - inner_loop.push_back(loop_idx->second); - } - - offset = outer_loop.size() - inner_loop.size(); - if (offset < 0) - return outer_loop; - for (int i=0; i& output_idx) { - if (output_idx.size() != 3) { - spdlog::error("Unsupported type operation... Can't zero skip"); - exit(EXIT_FAILURE); - } - uint32_t m, n, k; - m = output_idx.at(0); - n = output_idx.at(1); - k = output_idx.at(2); - auto attr_file = tog_parser->get_attribute_file(); - - if (!attr_file["zero_skip"]) { - return false; - } - - YAML::Node zero_skip = attr_file["zero_skip"]; - bool found_arg0 = false; - if (zero_skip["arg0"]) { - YAML::Node arg0 = zero_skip["arg0"]; - std::string m_str = std::to_string(m); - std::string k_str = std::to_string(k); - if (arg0[m_str] && arg0[m_str][k_str]) { - found_arg0 = true; - } - } - - bool found_arg1 = false; - if (zero_skip["arg1"]) { - YAML::Node arg1 = zero_skip["arg1"]; - std::string k_str = std::to_string(k); - std::string n_str = std::to_string(n); - if (arg1[k_str] && arg1[k_str][n_str]) { - found_arg1 = true; - } - } - - return found_arg0 || found_arg1; -} - -TileNode::TileNode(onnx::NodeProto& node) { - _type = get_tile_type(node.op_type()); - for (auto attribute : node.attribute()) { - if (attribute.name() == "torchsim_name") { - _name = attribute.s(); - break; - } - } - - /* insert input name */ - for (auto input : node.input()) { - _parent_name.push_back(input); - } - - /* insert output name */ - for (auto output : node.output()) { - _child_name.push_back(output); - } -} - -TileType TileNode::get_tile_type(std::string type) { - if (type == "loop_index_node") - return TileType::LOOP_INDEX_NODE; - else if (type == "loop_end_node") - return TileType::LOOP_END_NODE; - else if (type == "load_node") - return TileType::LOAD_NODE; - else if (type == "store_node") - return TileType::STORE_NODE; - else if (type == "compute_node") - return TileType::COMPUTE_NODE; - else if (type == "memory_wait_node") - return TileType::MEMORY_WAIT_NODE; - else if (type == "stonne_node") - return TileType::STONNE_NODE; - else if (type == "stonne_trace_compute_node") - return TileType::STONNE_TRACE_COMPUTE_NODE; - else if (type == "stonne_trace_load_node") - return TileType::STONNE_TRACE_LOAD_NODE; - else if (type == "stonne_trace_store_node") - return TileType::STONNE_TRACE_STORE_NODE; - spdlog::error("[TileGraphParser] Invalid node type..."); - exit(EXIT_FAILURE); -} - -void TileNode::print_node() { - std::string spaces(_depth, '\t'); - spdlog::debug("{}Node type: {}, name: {}", spaces, int(_type), _name); - spdlog::debug("{} input_name: {}", spaces, _parent_name); - spdlog::debug("{} output_name: {}", spaces, _child_name); - - for (auto& parent_ptr: _parent) { - spdlog::debug("{} parent: {}", spaces, parent_ptr->get_name()); - } - for (auto& child_ptr: _child) { - spdlog::debug("{} child: {}", spaces, child_ptr->get_name()); - } - if (_owner_loop != nullptr) - spdlog::debug("{} owner: {}", spaces, _owner_loop->get_name()); - else - spdlog::debug("{} owner: NULL", spaces); -} - -TileComputeNode::TileComputeNode(onnx::NodeProto& node) : TileNode(node) { - for (auto attribute : node.attribute()) { - if (attribute.name() == "torchsim_cycle") { - _cycle = int(attribute.i()); - } - if (attribute.name() == "torchsim_compute_type") { - _compute_type = attribute.i(); - } - if (attribute.name() == "torchsim_overlapping_cycle") { - _overlapping_cycle = attribute.i(); - } - } -} - -void TileComputeNode::print_node() { - TileNode::print_node(); - std::string spaces(get_depth(), '\t'); - spdlog::debug("{} compute_cycle: {}", spaces, _cycle); -} - -TileMemoryNode::TileMemoryNode(onnx::NodeProto& node) : TileNode(node) { - for (auto attribute : node.attribute()) { - if (attribute.name() == "torchsim_base_addr") { - _base_addr_name = attribute.s(); - } else if (attribute.name() == "torchsim_element_size") { - _elem_bits = static_cast(attribute.i()); - } else if (attribute.name() == "torchsim_tile_size") { - for (int i = 0; i < attribute.ints_size(); i++) - _tile_size.push_back(attribute.ints(i)); - } else if (attribute.name() == "torchsim_tile_stride") { - for (int i = 0; i < attribute.ints_size(); i++) - _tile_stride.push_back(attribute.ints(i)); - } else if (attribute.name() == "torchsim_tag_idx_list") { - for (int i = 0; i < attribute.strings_size(); i++) - _tag_idx_list.push_back(attribute.strings(i)); - } else if (attribute.name() == "torchsim_tag_stride_list") { - for (int i = 0; i < attribute.ints_size(); i++) - _tag_stride_list.push_back(static_cast(attribute.ints(i))); - } else if (attribute.name() == "torchsim_loop_idx_list") { - for (int i = 0; i < attribute.strings_size(); i++) - _loop_idx_list.push_back(attribute.strings(i)); - } else if (attribute.name() == "torchsim_loop_stride_list") { - for (int i = 0; i < attribute.ints_size(); i++) - _loop_stride_list.push_back(attribute.ints(i)); - } else if (attribute.name() == "torchsim_is_async") { - _is_async = attribute.i(); - } else if (attribute.name() == "torchsim_indirect_mode") { - _is_indirect = attribute.i(); - } else if (attribute.name() == "torchsim_name") { - } else { - spdlog::info("Unknown attribute: {}", attribute.name()); - } - } -} - -void TileMemoryNode::print_node() { - TileNode::print_node(); - std::string spaces(get_depth(), '\t'); - spdlog::debug("{} base_addr_name: {}", spaces, _base_addr_name); - spdlog::debug("{} elem_bits: {}", spaces, _elem_bits); - spdlog::debug("{} loop_stride_list: {} ", spaces, _loop_stride_list); - spdlog::debug("{} tile_size: {} ", spaces, _tile_size); - spdlog::debug("{} tile_stride: {} ", spaces, _tile_stride); - spdlog::debug("{} tag_list: {}", spaces, fmt::join(_tag_idx_list, ", ")); - spdlog::debug("{} tag_stride_list: {}", spaces, fmt::join(_tag_stride_list, ", ")); - spdlog::debug("{} index_list: {}", spaces, fmt::join(_loop_idx_list, ", ")); - spdlog::debug("{} indirect mode: {}", spaces, _is_indirect); -} - -TileMemoryWaitNode::TileMemoryWaitNode(onnx::NodeProto& node) : TileNode(node) { - for (auto attribute : node.attribute()) { - if (attribute.name() == "torchsim_tag_idx_list") { - for (int i = 0; i < attribute.strings_size(); i++) - _tag_idx_list.push_back(attribute.strings(i)); - } else if (attribute.name() == "torchsim_tag_stride_list") { - for (int i = 0; i < attribute.ints_size(); i++) - _tag_stride_list.push_back(static_cast(attribute.ints(i))); - } else if (attribute.name() == "torchsim_tag_divider_list") { - for (int i = 0; i < attribute.ints_size(); i++) - _tag_divider_list.push_back(static_cast(attribute.ints(i))); - } else if (attribute.name() == "torchsim_base_addr") { - _base_addr_name = attribute.s(); - } - } -} - -void TileStonneNode::print_node() { - TileNode::print_node(); - std::string spaces(get_depth(), '\t'); - - spdlog::debug("{} operation: {}", spaces, static_cast(desc.operation)); - spdlog::debug("{} layer_name: {}", spaces, desc.layer_name); - spdlog::debug("{} mem_init: {}", spaces, desc.mem_init); - - // Convolution Parameters - spdlog::debug("{} R: {}, S: {}, C: {}, K: {}, G: {}, N: {}", spaces, desc.R, desc.S, desc.C, desc.K, desc.G, desc.N); - spdlog::debug("{} X: {}, Y: {}, X_: {}, Y_: {}, strides: {}", spaces, desc.X, desc.Y, desc.X_, desc.Y_, desc.strides); - - // Convolution Tile Parameters - spdlog::debug("{} T_R: {}, T_S: {}, T_C: {}, T_K: {}, T_G: {}, T_N: {}", spaces, desc.T_R, desc.T_S, desc.T_C, desc.T_K, desc.T_G, desc.T_N); - spdlog::debug("{} T_X_: {}, T_Y_: {}", spaces, desc.T_X_, desc.T_Y_); - - // GEMM Parameters - spdlog::debug("{} GEMM_K: {}, GEMM_N: {}, GEMM_M: {}", spaces, desc.GEMM_K, desc.GEMM_N, desc.GEMM_M); - spdlog::debug("{} GEMM_T_K: {}, GEMM_T_N: {}, GEMM_T_M: {}", spaces, desc.GEMM_T_K, desc.GEMM_T_N, desc.GEMM_T_M); - - // Memory Addresses - spdlog::debug("{} matrix_a_dram_address: {}", spaces, desc.matrix_a_dram_address); - spdlog::debug("{} matrix_b_dram_address: {}", spaces, desc.matrix_b_dram_address); - spdlog::debug("{} matrix_c_dram_address: {}", spaces, desc.matrix_c_dram_address); - spdlog::debug("{} mem_matrix_c_file_name: {}", spaces, desc.mem_matrix_c_file_name); - - // Bitmap and CSR Data - spdlog::debug("{} bitmap_matrix_a_init: {}", spaces, desc.bitmap_matrix_a_init); - spdlog::debug("{} bitmap_matrix_b_init: {}", spaces, desc.bitmap_matrix_b_init); - spdlog::debug("{} rowpointer_matrix_a_init: {}", spaces, desc.rowpointer_matrix_a_init); - spdlog::debug("{} colpointer_matrix_a_init: {}", spaces, desc.colpointer_matrix_a_init); - spdlog::debug("{} rowpointer_matrix_b_init: {}", spaces, desc.rowpointer_matrix_b_init); - spdlog::debug("{} colpointer_matrix_b_init: {}", spaces, desc.colpointer_matrix_b_init); - spdlog::debug("{} trace_path: {}", spaces, desc.trace_path); -} - -void TileMemoryWaitNode::print_node() { - TileNode::print_node(); - std::string spaces(get_depth(), '\t'); - spdlog::debug("{} tag_idx_list: {}", spaces, fmt::join(_tag_idx_list, ", ")); - spdlog::debug("{} tag_stride_list: {}", spaces, fmt::join(_tag_stride_list, ", ")); -} - -void TileStonneTraceComputeNode::print_node() { - TileNode::print_node(); - std::string spaces(get_depth(), '\t'); - spdlog::debug("{} ComputeCycle: {}", spaces, _cycle); -} - -void TileStonneTraceMemoryNode::print_node() { - TileNode::print_node(); - std::string spaces(get_depth(), '\t'); - spdlog::debug("{} Address: {}", spaces, fmt::join(trace_address, ", ")); -} - -TileLoopNode::TileLoopNode(onnx::NodeProto& node) : TileNode(node) { - for (auto attribute : node.attribute()) { - if (attribute.name() == "torchsim_start") { - _start = attribute.i(); - } else if (attribute.name() == "torchsim_end") { - _end = attribute.i(); - } else if (attribute.name() == "torchsim_stride") { - _stride = attribute.i(); - } else if (attribute.name() == "torchsim_loop_idx") { - _tile_index_name = attribute.s(); - } else if (attribute.name() == "torchsim_loop_type") { - if (attribute.s() == "outer_loop") { - _loop_type = LoopType::PARALLEL_LOOP; - } else if (attribute.s() == "accumulation_loop") { - _loop_type = LoopType::ACCUMULATION_LOOP; - } else if (attribute.s() == "inner_loop") { - _loop_type = LoopType::INNER_LOOP; - } else { - _loop_type = LoopType::NORMAL_LOOP; - } - } - } -} - -std::vector> TileLoopNode::get_tiles_from_iter(TileGraphParser* tog_parser, std::map& iter) { - std::vector> tile_vec; - tile_vec.push_back(std::make_shared(Tile::Status::INITIALIZED)); - - std::map, std::shared_ptr> link_map; - for (auto& tile_node: _body_node) { - if (tile_node->get_type() == TileType::LOAD_NODE) { - std::shared_ptr mem_node = std::static_pointer_cast(tile_node); - std::vector iter_list; - int nr_inner_loop = 0; - auto& loop_idx_list = mem_node->get_loop_idx_list(); - for (auto loop_idx: loop_idx_list) { - int iter_value = getLoopIndexValue(iter, loop_idx); - iter_list.push_back(iter_value); - if (tog_parser->get_loop_type(loop_idx)==LoopType::INNER_LOOP) - nr_inner_loop++; - } - - /* Base address setting */ - std::string base_addr_name = mem_node->get_base_addr_name(); - int64_t base_addr_id = tog_parser->register_addr_name(base_addr_name); - addr_type base_addr = tog_parser->lookup(base_addr_name); - addr_type offset = std::inner_product(iter_list.begin(), iter_list.end(), mem_node->get_loop_stride_list().begin(), 0); - - std::vector tag_list; - std::vector accum_tag_list; - std::vector outer_loop_idx; - std::vector outer_loop_size; - /* Add accumulation loop info to accum_tag list */ - for (auto loop_idx = loop_idx_list.begin(); - loop_idx != loop_idx_list.end() - nr_inner_loop; ++loop_idx) { - // Check loop type and process - if (tog_parser->get_loop_type(*loop_idx)==LoopType::ACCUMULATION_LOOP) { - auto iter_value = getLoopIndexValue(iter, *loop_idx); - accum_tag_list.push_back(iter_value); - } - } - /* Default accum tag */ - if (accum_tag_list.empty()) { - accum_tag_list.push_back(0); - } - - for (auto loop_idx = loop_idx_list.begin(); - loop_idx != loop_idx_list.end(); ++loop_idx) { - if (tog_parser->get_loop_type(*loop_idx)==LoopType::PARALLEL_LOOP) { - uint32_t step = (uint32_t)tog_parser->get_loop_step(*loop_idx); - auto iter_value = getLoopIndexValue(iter, *loop_idx) / step; - outer_loop_idx.push_back(iter_value); - outer_loop_size.push_back(tog_parser->get_loop_size(*loop_idx)); - } - } - - uint32_t systolic_size = std::stoi(tog_parser->getMetaByName("systolic_size")); - for (auto loop_idx: mem_node->get_tag_idx_list()) { - if (iter.find(loop_idx) == iter.end()) - tag_list.push_back(0); - else { - uint32_t step = (uint32_t)tog_parser->get_loop_step(loop_idx); - step = step > systolic_size ? systolic_size : step; - auto iter_value = getLoopIndexValue(iter, loop_idx) / step; - tag_list.push_back(iter_value); - } - } - - /* Calc numa id */ - int numa_id = 0; - auto numa_stride_size = tog_parser->lookupNumaInfo(base_addr_name).size(); - if (numa_stride_size) { - int total_idx = calculateAddress(outer_loop_size, outer_loop_idx); - int stride_idx = calculateAddress(outer_loop_size, tog_parser->lookupNumaInfo(base_addr_name)); - numa_id = total_idx / stride_idx; - } - - /* Check need to make this memory node */ - std::vector& tag_stride_list = mem_node->get_tag_stride_list(); - std::vector key = tog_parser->calc_tag(accum_tag_list, tag_list, tag_stride_list); - if (tog_parser->check_memory_tag(base_addr_name, key)) - continue; - tog_parser->register_memory_tag(base_addr_name, key); - - printIndexMap("[TOGParser] Load Node " + mem_node->get_base_addr_name() + " Numa_id: " + std::to_string(numa_id), iter); - spdlog::trace("[TOGParser] Load Node {}({}) key = [{}], accum = [{}], tag = [{}], stride = [{}]", mem_node->get_base_addr_name(), - base_addr_id, - fmt::join(key, ", "), - fmt::join(accum_tag_list, ", "), - fmt::join(tag_list, ", "), - fmt::join(tag_stride_list, ", ")); - std::shared_ptr inst = std::make_shared( - Opcode::MOVIN, 0, - 0, base_addr+offset, - mem_node->get_tile_size(), mem_node->get_tile_stride(), mem_node->get_elem_bits(), - tag_list, tag_stride_list, accum_tag_list - ); - inst->set_addr_name(base_addr_name, base_addr_id); - inst->prepare_tag_key(); - inst->set_nr_inner_loop(nr_inner_loop); - inst->set_is_async(mem_node->is_async_node()); - inst->set_numa_id(numa_id); - - if (mem_node->is_indirect()) { - inst->set_indirect_index_path(tog_parser->get_indirect_path()); - tog_parser->inc_indirect_counter(); - } else { - bool is_sparse_tile = tog_parser->is_sparse_tile(tog_parser->get_dma_counter()); - tog_parser->inc_dma_counter(); - if (is_sparse_tile) { - inst->set_sparse_state(is_sparse_tile); - } - } - link_map[tile_node] = inst; - tile_vec.back()->append_instuction(inst); - } else if (tile_node->get_type() == TileType::STORE_NODE) { - std::shared_ptr mem_node = std::static_pointer_cast(tile_node); - std::vector iter_list; - std::vector outer_loop_idx; - std::vector outer_loop_size; - int nr_inner_loop = 0; - auto& loop_idx_list = mem_node->get_loop_idx_list(); - for (auto loop_idx: loop_idx_list) { - auto iter_value = getLoopIndexValue(iter, loop_idx); - iter_list.push_back(iter_value); - if (tog_parser->get_loop_type(loop_idx)==LoopType::INNER_LOOP) - nr_inner_loop++; - if (tog_parser->get_loop_type(loop_idx)==LoopType::PARALLEL_LOOP) { - uint32_t step = (uint32_t) tog_parser->get_loop_step(loop_idx); - auto iter_value = getLoopIndexValue(iter, loop_idx) / step; - outer_loop_idx.push_back(iter_value); - outer_loop_size.push_back(tog_parser->get_loop_size(loop_idx)/ step); - } - } - - /* Lookup given name's address */ - std::string base_addr_name = mem_node->get_base_addr_name(); - int64_t base_addr_id = tog_parser->register_addr_name(base_addr_name); - addr_type base_addr = tog_parser->lookup(base_addr_name); - addr_type offset = std::inner_product(iter_list.begin(), iter_list.end(), mem_node->get_loop_stride_list().begin(), 0); - - /* Calc numa id */ - int numa_id = 0; - auto numa_stride_size = tog_parser->lookupNumaInfo(base_addr_name).size(); - if (numa_stride_size) { - int total_idx = calculateAddress(outer_loop_size, outer_loop_idx); - int stride_idx = calculateAddress(outer_loop_size, tog_parser->lookupNumaInfo(base_addr_name)); - numa_id = total_idx / stride_idx; - } - - printIndexMap("[TOGParser] Store Node " + mem_node->get_base_addr_name() + " Numa_id: " + std::to_string(numa_id), iter); - std::shared_ptr inst = std::make_shared( - Opcode::MOVOUT, 0, - 0, base_addr+offset, - mem_node->get_tile_size(), mem_node->get_tile_stride(), mem_node->get_elem_bits(), - std::vector(1, 0), mem_node->get_tag_stride_list(), std::vector() - ); - inst->set_addr_name(base_addr_name, base_addr_id); - inst->prepare_tag_key(); - inst->set_nr_inner_loop(nr_inner_loop); - inst->set_is_async(mem_node->is_async_node()); - inst->set_numa_id(numa_id); - if (mem_node->is_indirect()) { - inst->set_indirect_index_path(tog_parser->get_indirect_path()); - tog_parser->inc_indirect_counter(); - } - link_map[tile_node] = inst; - tile_vec.back()->append_instuction(inst); - } else if (tile_node->get_type() == TileType::MEMORY_WAIT_NODE) { - printIndexMap("[TOGParser] DMA Wait Node ", iter); - std::shared_ptr wait_node = std::static_pointer_cast(tile_node); - auto base_addr_name = wait_node->get_base_addr_name(); - int64_t base_addr_id = tog_parser->register_addr_name(base_addr_name); - addr_type base_addr = tog_parser->lookup(base_addr_name); - /* Lookup given name's address */ - std::vector iter_list; - std::vector tag_list; - std::vector& tag_stride_list = wait_node->get_tag_stride_list(); - std::vector& tag_divider_list = wait_node->get_tag_divider_list(); - std::vector new_tag_stride_list; - std::vector accum_tag_list; - auto& wait_tag_list = wait_node->get_tag_idx_list(); - - for (int i=0; iget_loop_type(loop_idx)==LoopType::ACCUMULATION_LOOP) { - auto iter_value = getLoopIndexValue(iter, loop_idx); - accum_tag_list.push_back(iter_value); - } else { - auto iter_value = getLoopIndexValue(iter, loop_idx) / tag_divider_list.at(i); - tag_list.push_back(iter_value); - } - } - /* Default accum tag */ - if (accum_tag_list.empty()) { - accum_tag_list.push_back(0); - } - - /* Skip accum stride */ - for (auto i : tag_stride_list) { - if (i!=-1) - new_tag_stride_list.push_back(i); - } - - spdlog::trace("[TOGParser] Wait Node {}, accum = [{}], tag = [{}], stride = [{}]", wait_node->get_base_addr_name(), - fmt::join(accum_tag_list, ", "), - fmt::join(tag_list, ", "), - fmt::join(new_tag_stride_list, ", ")); - - std::shared_ptr inst = std::make_shared( - Opcode::MEMORY_BAR, 0, - 0, base_addr, - std::vector(), std::vector(), 0, - tag_list, new_tag_stride_list, accum_tag_list - ); - inst->set_addr_name(base_addr_name, base_addr_id); - inst->prepare_tag_key(); - link_map[tile_node] = inst; - tile_vec.back()->append_instuction(inst); - } else if (tile_node->get_type() == TileType::COMPUTE_NODE) { - printIndexMap("[TOGParser] Compute Node ", iter); - std::shared_ptr compute_node = std::static_pointer_cast(tile_node); - std::vector tag_list = {0}; - std::vector tag_stride_list = {1}; - std::vector accum_tag_list; - std::shared_ptr inst = std::make_shared( - Opcode::COMP, compute_node->get_cycle(), - 0, 0, - std::vector(), std::vector(), 0, - tag_list, tag_stride_list, accum_tag_list - ); - inst->set_overlapping_cycle(compute_node->get_overlapping_cycle()); - inst->set_compute_type(compute_node->get_compute_type()); - - link_map[tile_node] = inst; - tile_vec.back()->append_instuction(inst); - } else if (tile_node->get_type() == TileType::LOOP_INDEX_NODE) { - std::shared_ptr loop_node = std::static_pointer_cast(tile_node); - uint64_t start = loop_node->get_start(); - uint64_t stride = loop_node->get_stride(); - uint64_t end = loop_node->get_end(); - - /* Create tile before enter nested loop */ - for (const auto& pair: link_map) { - std::shared_ptr node = pair.first; - std::shared_ptr inst = pair.second; - - /* Link instruction dependency */ - for (const auto& child_node: node->get_child()) { - if (link_map.find(child_node) != link_map.end()) { - std::shared_ptr child_inst = link_map[child_node]; - inst->add_dep(child_inst, DepEvent::DONE); - } - } - } - link_map.clear(); - /* iterate nested loop */ - std::shared_ptr parent = tile_vec.back(); - std::shared_ptr child = std::make_shared(Tile::Status::INITIALIZED); - - std::map inner_indices = iter; - auto loop_type = loop_node->get_loop_type(); - auto& parent_instructions = parent->get_instructions(); - auto& last_instruction = parent_instructions.back(); - auto nr_inst = parent_instructions.size(); - for (int i=start; iget_idx_name()] = i; - std::vector> ret = loop_node->get_tiles_from_iter(tog_parser, inner_indices); - if (loop_type == LoopType::INNER_LOOP) { - for (const auto& inner_tile : ret) { - for (auto& inner_inst : inner_tile->get_instructions()) { - tile_vec.back()->append_instuction(inner_inst); - if (nr_inst) { - last_instruction->add_dep(inner_inst, DepEvent::DONE); - } - } - } - } else { - parent->append_child(ret.front()); - ret.back()->append_child(child); - for (const auto& inner_tile : ret) { - tile_vec.push_back(inner_tile); - } - } - } - - parent->append_child(child); - /* Create new tile */ - tile_vec.push_back(child); - } else if (tile_node->get_type() == TileType::STONNE_NODE) { - printIndexMap("[TOGParser] Stonne Node ", iter); - std::shared_ptr stonne_node = std::static_pointer_cast(tile_node); - std::shared_ptr inst = std::make_shared(Opcode::COMP); - link_map[tile_node] = inst; - tile_vec.back()->append_instuction(inst); - tile_vec.back()->set_custom_data(stonne_node->getDesc()); - tile_vec.back()->set_stonne_tile(true); - } else if (tile_node->get_type() == TileType::STONNE_TRACE_COMPUTE_NODE) { - std::shared_ptr stonne_node = std::static_pointer_cast(tile_node); - std::shared_ptr inst = std::make_shared(Opcode::COMP); - inst->set_compute_cycle(stonne_node->get_cycle()); - link_map[tile_node] = inst; - tile_vec.back()->append_instuction(inst); - tile_vec.back()->set_stonne_tile(true); - } else if (tile_node->get_type() == TileType::STONNE_TRACE_LOAD_NODE) { - std::shared_ptr stonne_node = std::static_pointer_cast(tile_node); - std::shared_ptr inst = std::make_shared(Opcode::MOVIN); - inst->set_trace_address(stonne_node->get_address()); - link_map[tile_node] = inst; - tile_vec.back()->append_instuction(inst); - tile_vec.back()->set_stonne_tile(true); - } else if (tile_node->get_type() == TileType::STONNE_TRACE_STORE_NODE) { - std::shared_ptr stonne_node = std::static_pointer_cast(tile_node); - std::shared_ptr inst = std::make_shared(Opcode::MOVOUT); - inst->set_trace_address(stonne_node->get_address()); - link_map[tile_node] = inst; - tile_vec.back()->append_instuction(inst); - tile_vec.back()->set_stonne_tile(true); - } - } - - for (const auto& pair: link_map) { - std::shared_ptr node = pair.first; - std::shared_ptr inst = pair.second; - - /* Link instruction dependency */ - for (const auto& child_node: node->get_child()) { - if (link_map.find(child_node) != link_map.end()) { - std::shared_ptr child_inst = link_map[child_node]; - inst->add_dep(child_inst, DepEvent::DONE); - } - } - } - - return tile_vec; -} - -void TileLoopNode::print_node() { - TileNode::print_node(); - std::string spaces(get_depth(), '\t'); - spdlog::debug("{} loop_idx: {} ", spaces, _tile_index_name); - spdlog::debug("{} start: {} ", spaces, _start); - spdlog::debug("{} end: {} ", spaces, _end); - spdlog::debug("{} stride: {} ", spaces, _stride); -} - -TileGraphParser::TileGraphParser(std::string onnx_path, std::string attribute_path, const YAML::Node& config_yaml) { - loadConfig(attribute_path, _attribute_config); - _config_yaml = config_yaml; // Use the pre-loaded config - _attribute_path = attribute_path; - - if (!std::filesystem::exists(onnx_path)) { - throw std::runtime_error("Error: TOG graph path not found: " + onnx_path); - } - /* Note: this parsing algorithm assume that all node are sorted in topological-order */ - std::ifstream model_istream(onnx_path); - google::protobuf::io::IstreamInputStream zero_copy_input(&model_istream); - onnx::ModelProto model_proto; - - /* Attribute parsing */ - if (_attribute_config["address_info"]) { - const auto& address_info = _attribute_config["address_info"]; - for (YAML::const_iterator it = address_info.begin(); it != address_info.end(); ++it) { - std::string key = it->first.as(); - uint64_t value = it->second.as(); - - _arg_to_address[key] = value; - spdlog::trace("[TOGParser/Attribute] Address Attribute key: {} address: 0x{:x}", key, value); - } - } - - if (_attribute_config["address_numa_stride"]) { - const auto& address_numa_stride = _attribute_config["address_numa_stride"]; - for (YAML::const_iterator it = address_numa_stride.begin(); it != address_numa_stride.end(); ++it) { - std::string key = it->first.as(); - const auto& value_list = it->second; // YAML Sequence Node - - for (const auto& val : value_list) { - _arg_numa_stride[key].push_back(val.as()); - } - spdlog::trace("[TOGParser/Attribute] Address numa info key: {} numa stride : {}", key, fmt::join(_arg_numa_stride[key], ", ")); - } - } - - if (_attribute_config["sram_alloc"] && - _config_yaml["l2d_type"] && - _config_yaml["l2d_type"].as() == "datacache") { - - auto sram_alloc_list = _attribute_config["sram_alloc"]; - spdlog::info("[TOGParser/Attribute] ================= SRAM Alloc Plan ================"); - - for (YAML::const_iterator it = sram_alloc_list.begin(); it != sram_alloc_list.end(); ++it) { - std::string key = it->first.as(); - const auto& value_list = it->second; // List [start, end] - - unsigned long long start = value_list[0].as(); - unsigned long long end = value_list[1].as(); - - spdlog::info("[TOGParser/Attribute] {:16s}: 0x{:016x} ~ 0x{:016x}", key, start, end); - Interval entry = {start, end, 0}; - _cache_plan.push_back(entry); - } - } - load_sparse_meta_data(); - - /* TOG file parsing */ - _tog_path = onnx_path; - model_proto.ParseFromZeroCopyStream(&zero_copy_input) && model_istream.eof(); - - auto input = model_proto.graph().input(); - auto graph_name = model_proto.graph().name(); - graph_name = graph_name == "" ? "?" : graph_name; - - /* Get meta data from graph */ - for (const auto& meta : model_proto.metadata_props()) { - spdlog::trace("[TOGParser] Register Metadata \"{}\": \"{}\"", meta.key(), meta.value()); - _tog_meta[meta.key()] = meta.value(); - } - - for (onnx::NodeProto node_proto : model_proto.graph().node()) { - std::string op_type = node_proto.op_type(); - TileType type = TileNode::get_tile_type(op_type); - /* Parse node */ - if (type == TileType::LOOP_INDEX_NODE) { - std::shared_ptr tile_node = std::make_shared(node_proto); - - /* Register output */ - register_tile(tile_node); - register_loop(tile_node); - increase_loop_top(); - - /* Register loop info to parser */ - std::string loop_idx = tile_node->get_idx_name(); - uint64_t start = tile_node->get_start(); - uint64_t end = tile_node->get_end(); - uint64_t step = tile_node->get_stride(); - _loop_size_map[loop_idx] = std::tuple(end - start, step, tile_node->get_loop_type()); - } else if (type == TileType::LOOP_END_NODE) { - std::shared_ptr tile_node = std::make_shared(node_proto); - register_tile(tile_node); - decrease_loop_top(); - } else if (type == TileType::LOAD_NODE || type == TileType::STORE_NODE) { - std::shared_ptr tile_node = std::make_shared(node_proto); - /* Register output */ - register_tile(tile_node); - } else if (type == TileType::COMPUTE_NODE) { - std::shared_ptr tile_node = std::make_shared(node_proto); - /* Register output */ - register_tile(tile_node); - } else if (type == TileType::MEMORY_WAIT_NODE) { - std::shared_ptr tile_node = std::make_shared(node_proto); - /* Register output */ - register_tile(tile_node); - } else if (type == TileType::STONNE_NODE) { - std::shared_ptr tile_node = std::make_shared(node_proto); - /* Register output */ - register_tile(tile_node); - } else if (type == TileType::STONNE_TRACE_COMPUTE_NODE) { - std::shared_ptr tile_node = std::make_shared(node_proto); - /* Register output */ - register_tile(tile_node); - } else if (type == TileType::STONNE_TRACE_LOAD_NODE) { - std::shared_ptr tile_node = std::make_shared(node_proto); - /* Register output */ - register_tile(tile_node); - } else if (type == TileType::STONNE_TRACE_STORE_NODE) { - std::shared_ptr tile_node = std::make_shared(node_proto); - /* Register output */ - register_tile(tile_node); - } - } - - for (auto tile: _tile_vec) { - if (tile->get_type() != TileType::LOOP_END_NODE) - tile->print_node(); - } - - _tile_graph = std::make_unique(TileGraph(onnx_path, graph_name)); - _tile_graph->init_cache_plan(_cache_plan); - if (std::stoi(this->getMetaByName("stonneGraph"))) - _tile_graph->StonneGraph=true; - - /* Generate subgraph */ - if (_loop_nodes.empty()) { - spdlog::warn("[TileGraphParser] Null Kernel \"{}\"", onnx_path); - return; - } - - int last_outer_idx = -1; - /* Extract outer loop */ - for (int i=0;i<_loop_nodes.size();i++) { - std::shared_ptr outer_loop = std::static_pointer_cast(_loop_nodes.at(i).front()); - if (outer_loop->get_loop_type() != LoopType::PARALLEL_LOOP) - break; - last_outer_idx = i; - std::string loop_idx = outer_loop->get_idx_name(); - uint64_t start = outer_loop->get_start(); - uint64_t end = outer_loop->get_end(); - uint64_t stride = outer_loop->get_stride(); - _tile_graph->push_range(loop_idx, {start, end, stride}); - spdlog::trace("[TOGParser] loop_idx: {}, start: {}, end: {}, stride: {}", loop_idx, start, end, stride); - } - - /* Iterate outer loop and initialize inner loop */ - for (auto iter=_tile_graph->begin(); iter!=_tile_graph->end(); ++iter) { - std::shared_ptr subgraph = std::make_shared(); - subgraph->set_core_id(getCoreIdFromConfig(_attribute_config, subgraph->get_id())); - auto indices = iter.get_indices(); - for (auto loop : _loop_nodes.at(last_outer_idx)) { - std::shared_ptr outer_loop = std::static_pointer_cast(loop); - this->clear_tag_table(); // Clear tag table for each inner loop - std::vector> sub_tiles = outer_loop->get_tiles_from_iter(this, indices); - - /* insert tiles to subgraph */ - for (const auto& sub_tile: sub_tiles){ - subgraph->add_tile(sub_tile); - sub_tile->set_owner(subgraph); - } - } - /* insert subgraph to graph */ - _tile_graph->append_subgraph(subgraph); - } -} - -void TileGraphParser::register_loop(std::shared_ptr loop_node) { - if (_loop_nodes.size() <= _loop_stack_pointer) { - _loop_nodes.resize(_loop_stack_pointer + 1); - } - _loop_nodes.at(_loop_stack_pointer).push_back(loop_node); -} - -void TileGraphParser::register_tile(std::shared_ptr tile_node) { - tile_node->set_depth(_loop_stack_pointer); - /* register output */ - for (std::string output_name : tile_node->get_child_name()) { - _output_map[output_name] = tile_node; - } - - /* register tile vec*/ - _tile_vec.push_back(tile_node); - - /* Update owner loop tile */ - tile_node->set_owner_loop(get_top_loop()); - std::shared_ptr owner = std::static_pointer_cast(tile_node->get_owner_loop()); - if (owner != nullptr) { - owner->add_body(tile_node); - } - - /* Skip loop end node */ - if (tile_node->get_type() == TileType::LOOP_END_NODE) - return; - - /* Link parent tile */ - for (std::string input_name : tile_node->get_parent_name()) { - std::shared_ptr parent = _output_map[input_name]; - if (parent->get_type() == TileType::LOOP_END_NODE) { - parent->get_owner_loop()->add_child(tile_node); - tile_node->add_parent(parent->get_owner_loop()); - } else if (parent->get_type() != TileType::LOOP_INDEX_NODE) { - parent->add_child(tile_node); - tile_node->add_parent(parent); - } - } -} - -std::vector TileGraphParser::calc_tag(std::vector& accum_tag, std::vector& tag_idx, std::vector& tag_stride) { - int64_t key_offset = 0; - std::vector tag_key; - for (size_t i = 0; i < tag_idx.size(); i++) - key_offset += tag_idx.at(i) * tag_stride.at(i); - for (auto accum_dim : accum_tag) - tag_key.push_back(accum_dim); - tag_key.push_back(key_offset); - return tag_key; -} - -void TileGraphParser::register_memory_tag(std::string name, std::vector& tag_key) { - assert(_tag_table.find(std::make_pair(name, tag_key))==_tag_table.end()); - _tag_table[std::make_pair(name, tag_key)] = true; -} - -bool TileGraphParser::check_memory_tag(std::string name, std::vector& tag_key) { - return _tag_table.find(std::make_pair(name, tag_key))==_tag_table.end() ? false : true; -} - -std::shared_ptr TileGraphParser::get_top_loop() { - if (_loop_nodes.empty()) - return nullptr; - return _loop_nodes.at(_loop_stack_pointer-1).back(); -} - -addr_type TileGraphParser::lookup(std::string key) { - try { - return _arg_to_address.at(key); - } catch (const std::out_of_range& e) { - spdlog::warn("[TOGParser] Key not found {} in the \"{}\"", key, _tog_path); - _arg_to_address[key] = 0; - return 0; - } -} - -const std::vector& TileGraphParser::lookupNumaInfo(std::string key) { - static std::vector dummy_result = {}; - auto val = _arg_numa_stride.find(key); - if (val == _arg_numa_stride.end()) - return dummy_result; - return _arg_numa_stride.at(key); -} - -int TileGraphParser::getCoreIdFromConfig(const YAML::Node& attribute_config, int subgraph_id) { - std::string key = std::to_string(subgraph_id); - if (attribute_config["subgraph_map"]) { - const auto& subgraph_map = attribute_config["subgraph_map"]; - if (subgraph_map[key]) { - return subgraph_map[key].as(); - } - } - return -1; -} \ No newline at end of file diff --git a/TOGSim/src/main.cc b/TOGSim/src/main.cc index 93be89c2d..82d63d1dc 100644 --- a/TOGSim/src/main.cc +++ b/TOGSim/src/main.cc @@ -7,7 +7,6 @@ #include #include "Simulator.h" -#include "TileGraphParser.h" #include "helper/CommandLineParser.h" #include "togsim_loader.h" // P3 trace pipeline: run a compiled producer .so #include "togsim_trace_bridge.h" // ... and bridge its trace to a TileGraph @@ -59,25 +58,18 @@ std::unique_ptr build_trace_tilegraph(Simulator* simulator, "trace_kernel"); } -// A kernel dir with a trace.so runs it (a refused or failing producer is an error, never an -// ONNX fallback); the DEPRECATED legacy ONNX TOG serves a dir without one, or TORCHSIM_LEGACY_TOG=1. void launchKernel(Simulator* simulator, unsigned int kernel_id, std::string onnx_path, std::string attribute_path, const YAML::Node& config_yaml, cycle_type request_time=0, int partition_id=0, int device_id=0) { - std::unique_ptr tile_graph; - std::string tog_path = onnx_path; - const char* legacy = std::getenv("TORCHSIM_LEGACY_TOG"); + // The kernel's trace.so / trace_cycles.tsv sit in the directory of the handle it is launched with. std::string dir = fs::path(onnx_path).parent_path().string(); std::string trace_so = dir + "/trace.so"; std::string cycle_tsv = dir + "/trace_cycles.tsv"; - if ((!legacy || std::string(legacy) != "1") && fs::exists(trace_so)) { - tile_graph = build_trace_tilegraph(simulator, trace_so, cycle_tsv, partition_id); - if (!tile_graph) - throw std::runtime_error(fmt::format("[TOGSim] trace producer run failed for {}", trace_so)); - tog_path = trace_so; - } else { - spdlog::warn("[TOGSim] using the DEPRECATED legacy ONNX TOG path for {}", onnx_path); - auto graph_praser = TileGraphParser(onnx_path, attribute_path, config_yaml); - tile_graph = std::move(graph_praser.get_tile_graph()); - } + if (!fs::exists(trace_so)) + throw std::runtime_error("[TOGSim] no trace.so next to " + onnx_path); + std::unique_ptr tile_graph = + build_trace_tilegraph(simulator, trace_so, cycle_tsv, partition_id); + if (!tile_graph) + throw std::runtime_error("[TOGSim] trace.so run failed for " + trace_so); + std::string tog_path = trace_so; tile_graph->set_arrival_time(request_time ? request_time : simulator->get_core_cycle()); tile_graph->set_kernel_id(kernel_id); spdlog::info("[Scheduler {}] Enqueued kernel_id: {}, tog_path: {}, operation: {}, request_time_cycles: {}", diff --git a/TOGSim/src/scheduler/Scheduler.cc b/TOGSim/src/scheduler/Scheduler.cc index 0be42f274..24bc19f45 100644 --- a/TOGSim/src/scheduler/Scheduler.cc +++ b/TOGSim/src/scheduler/Scheduler.cc @@ -12,7 +12,7 @@ void Scheduler::enqueue_graph(std::unique_ptr tile_graph) { const std::shared_ptr Scheduler::peek_tile(int core_id, int slot_id, CoreType ctype) { if (_tile_graph.empty() || _tile_graph.at(0)->get_arrival_time() > *_core_cycle) return std::make_unique(Tile(Tile::Status::EMPTY)); - if ((!_tile_graph.at(0)->StonneGraph && ctype == CoreType::WS_MESH) || (_tile_graph.at(0)->StonneGraph && ctype == CoreType::STONNE)) + if (ctype == CoreType::WS_MESH) return _tile_graph.at(0)->peek_tile(core_id, slot_id); return std::make_unique(Tile(Tile::Status::EMPTY)); } diff --git a/configs/heterogeneous_c2_simple_noc.yml b/configs/heterogeneous_c2_simple_noc.yml deleted file mode 100644 index d0d6d0f07..000000000 --- a/configs/heterogeneous_c2_simple_noc.yml +++ /dev/null @@ -1,30 +0,0 @@ -core_type: -- stonne -- ws_mesh -stonne_config_path: /workspace/PyTorchSim/TOGSim/extern/stonneCore/tests/sparseflex_op_128mses_128_bw.cfg -num_cores: 2 -core_freq_mhz: 940 -core_stats_print_period_cycles: 10000 -num_stonne_per_core: 8 -num_stonne_port: 64 -num_systolic_array_per_core: 2 - -vpu_num_lanes: 128 -vpu_spad_size_kb_per_lane: 128 -vpu_vector_length_bits: 256 - -dram_type: ramulator2 -dram_freq_mhz: 940 -dram_channels: 16 -dram_stats_print_period_cycles: 10000 -ramulator_config_path: ../configs/ramulator2_configs/HBM2_TPUv3.yaml - -icnt_type: simple -icnt_latency_cycles: 10 -icnt_freq_mhz: 940 -icnt_injection_ports_per_core: 16 -num_partition: 2 -partition: - core_0: 0 - core_1: 1 - diff --git a/configs/stonne_big_c1_simple_noc.yml b/configs/stonne_big_c1_simple_noc.yml deleted file mode 100644 index 9bbfd6df7..000000000 --- a/configs/stonne_big_c1_simple_noc.yml +++ /dev/null @@ -1,19 +0,0 @@ -core_type: -- stonne -stonne_config_path: /workspace/PyTorchSim/TOGSim/extern/stonneCore/tests/sparseflex_op_128mses_128_bw.cfg -num_cores: 1 -core_freq_mhz: 940 -core_stats_print_period_cycles: 10000 -num_stonne_per_core: 8 -num_stonne_port: 64 - -dram_type: ramulator2 -dram_freq_mhz: 940 -dram_channels: 8 -dram_stats_print_period_cycless: 10000 -ramulator_config_path: ../configs/ramulator2_configs/HBM2_TPUv3.yaml - -icnt_type: simple -icnt_latency_cycles: 10 -icnt_freq_mhz: 940 -icnt_injection_ports_per_core: 16 diff --git a/configs/stonne_single_c1_simple_noc.yml b/configs/stonne_single_c1_simple_noc.yml deleted file mode 100644 index f862d7a9b..000000000 --- a/configs/stonne_single_c1_simple_noc.yml +++ /dev/null @@ -1,19 +0,0 @@ -core_type: -- stonne -stonne_config_path: /workspace/PyTorchSim/TOGSim/extern/stonneCore/tests/sparseflex_op_128mses_128_bw.cfg -num_cores: 1 -core_freq_mhz: 700 -core_stats_print_period_cycles: 10000 -num_stonne_per_core: 1 -num_stonne_port: 8 - -dram_type: ramulator2 -dram_freq_mhz: 700 -dram_channels: 8 -dram_stats_print_period_cycles: 10000 -ramulator_config_path: ../configs/ramulator2_configs/HBM2_TPUv2.yaml - -icnt_type: simple -icnt_latency_cycles: 10 -icnt_freq_mhz: 700 -icnt_injection_ports_per_core: 8 diff --git a/configs/stonne_validation_c1_simple_noc.yml b/configs/stonne_validation_c1_simple_noc.yml deleted file mode 100644 index f86dcce10..000000000 --- a/configs/stonne_validation_c1_simple_noc.yml +++ /dev/null @@ -1,22 +0,0 @@ -core_type: -- stonne -stonne_config_path: /workspace/PyTorchSim/TOGSim/extern/stonneCore/tests/sparseflex_op_128mses_128_bw.cfg -num_cores: 1 -core_freq_mhz: 1000 -core_stats_print_period_cycles: 10000 -num_stonne_per_core: 1 -num_stonne_port: 32 - -dram_type: simple -dram_freq_mhz: 1000 -dram_channels: 1 -dram_req_size_byte: 32 -dram_latency: 100 -dram_stats_print_period_cycles: 10000 -l2d_type: datacache -l2d_config: S:128:128:64,32,L:T:m:W:L,A:192:4,32:0,32 - -icnt_type: simple -icnt_latency_cycles: 10 -icnt_freq_mhz: 1000 -icnt_injection_ports_per_core: 8 diff --git a/docs/design/togsim_cpp_trace.md b/docs/design/togsim_cpp_trace.md deleted file mode 100644 index 6b3bf2145..000000000 --- a/docs/design/togsim_cpp_trace.md +++ /dev/null @@ -1,558 +0,0 @@ -# TOGSim C++ Trace Generation - -TOGSim's timing path consumes a **Tile-Operation Graph (TOG)**: the stream of -modeled instructions a kernel executes (tile loads, tile computes, tile stores) -together with the dependency edges between them. The timing core turns that -graph into cycles. - -This document describes how the TOG is produced: the kernel's post-vcix MLIR is -compiled into a small C++ program, and *running* that program emits the graph. -It replaces an earlier producer that materialized a flattened graph at compile -time and serialized it as ONNX. - -Vocabulary used throughout: - -- **Producer** — the generated `.so`. Shape-parametric C++ compiled from the - kernel's MLIR. It contains no timing model and no functional compute; running - it emits a trace and nothing else. -- **Trace record** — one `togsim_*` callback invocation, i.e. one modeled - instruction. -- **Bridge** — the TOGSim-side code that turns the recorded trace into a - `TileGraph` of `Instruction`s with dependency edges. -- **Core** — TOGSim's existing timing model (systolic arrays, VPU, DMA engine, - SRAM, DRAM/NoC). It is unchanged by this pipeline. - -## 1. Motivation - -The legacy TOG producer (`MLIR -> Python dict -> ONNX -> C++ TileGraphParser`) -had four structural problems: - -1. **"ONNX in name only."** The graph was serialized as ONNX, but every op was a - custom `torchsim_*` attribute. That paid ONNX's costs (rigid schema, - protobuf, stringly-typed attributes) for none of its interop value. The - schema lived in three places — Python (`extension_op.py`), ONNX - (`AsmParser/onnx_utility.py`), C++ (`TileGraphParser`) — and drifted. - -2. **Synchronization was ad-hoc and DMA-specific.** One concept ("an async op - completed; a consumer may proceed") was expressed two different ways: a - content-addressed `tag_table` with overloaded magic values (`0` pending, `1` - signaled, `>1` consumed-count, `-1` sparse) plus a separate - `Instruction::ready_counter` / `child_inst` edge mechanism. Only the former - worked for DMA. - -3. **Static shape was baked in.** Loop bounds were resolved to constants and the - graph fully materialized per shape, so dynamic shape forced a recompile per - shape — pathological for LLM decode (a new `seq_len` every step) and MoE - (variable expert load). - -4. **Loop-flattening hacks.** `loop_end` tricks, the `calc_tag` content hash, - dedup-by-skip and magic offsets existed only to flatten loop nests into a - static graph. - -See [Appendix A](#appendix-a-legacy-path-references) for the file references. - -## 2. Model: trace-driven, not graph-materialized - -Rather than materializing a flattened graph, **the TOG becomes a stream emitted -by running a shape-parametric producer.** The producer keeps loops as loops -(symbolic bounds become C++ function parameters) and calls a small set of -callbacks. Each call emits one trace record. TOGSim `dlopen`s the producer, -injects a callback context, and records the stream. - -| Problem | Resolution | -|---|---| -| ONNX-in-name-only, 3-place schema | The C ABI is the single contract. No ONNX. | -| DMA-only, ad-hoc sync | Dependencies are explicit dataflow edges (§10). Async-DMA data arrival is one explicit barrier op keyed by the runtime tag slot. | -| Static shape | Loop bounds pass through from MLIR verbatim; symbolic bounds become native C++ loop bounds, so trip count is dynamic. | -| Loop-flatten hacks | Loops stay loops. `calc_tag` and dedup disappear. | - -This is **not** a dynamic hardware scheduler. Control flow is still statically -emitted by the compiler; the `.so` is a deterministic *trace generator*, not a -timing model. The trace-as-data boundary is preserved, so the timing core is -untouched. - -## 3. Trace op vocabulary - -Four primitives. Everything else is composition. - -- `dma(dir, arg_id, offset, shape, is_async, tag_id, tag_slot, read_bufs, - write_bufs)` — `dir ∈ {LOAD, STORE}`. A **synchronous** DMA is blocking: it - finishes when its data arrives, and consumers depend on it directly. An - **async** DMA returns control immediately and signals its tag at data arrival - (DMA response-complete); a later `memory_barrier` is the explicit point that - waits on it. -- `compute(tile_id, compute_type, dims, read_bufs, write_bufs)` — one fixed-size - tile kernel. Its cost is looked up (§6), never computed here. -- `memory_barrier(tag_id, tag_slot, write_bufs)` — the explicit async-DMA sync. - It waits until the async DMA carrying the same `(tag_id, tag_slot)` has - delivered its data, then becomes the last writer of the loaded buffer so - consumers gate on arrival. It is the source IR's `togsim.wait` mapped through, - not a synthesized barrier. -- `dispatch(tile_fn, iv, n_iv)` — run one parallel work-item (§9.3). - -Control flow lives in the producer: ordinary `for`/`if` with runtime bounds. - -Two things share the word "tag", and the pairing key is **both together**: - -- **`tag_id`** — compile-time identity of a DMA's tag memref (which logical - channel: the A-load vs the B-load). -- **`tag_slot`** — the runtime SRAM tile slot the loaded tile occupies (the - double-buffer / SRAM-capacity index). - -The key must include a runtime component: one static `togsim.dma` op executes -once per loop iteration, each iteration writing a different slot, so a -compile-time id alone cannot express the per-iteration pairing. - -`lower_to_vcix` writes the wait's tag index with a `-acc_iv` term per -accumulation (reduction) loop var — a sentinel marking the reduction axis, not -an arithmetic offset — and `build_skeleton` strips those terms so a -`memory_barrier` waits on the same slot its async load wrote. (The legacy -`TileGraphParser` mirrors this by skipping stride `-1`.) Without the strip, the -producer evaluates `-acc_iv` to a negative slot at reduction iteration > 0 and -the pairing fails on subtile + multi-tile-K. - -## 4. Decisions - -| Axis | Decision | -|---|---| -| Input MLIR | Use the **given MLIR as-is**. Do not touch inductor, the MLIR templates, or shape plumbing. Whatever bounds the MLIR carries (const or symbolic) pass through verbatim. | -| MLIR -> C++ | **EmitC dialect + `mlir-translate --mlir-to-cpp`** (upstream). | -| `.so` <-> TOGSim | **`dlopen` + an opaque `EmitCtx` callback context.** The ABI boundary is the main design surface. | -| `.so` role | **Timing trace only.** Functional correctness stays on the Spike/LLVM path. Every op without a timing dependency is stripped; the loop skeleton, the API ops, and the ops feeding bounds/addresses remain. | -| Compute cycle | A separate annotation pass reuses **gem5 sample-mode** to build a precomputed `tile_id -> cycle` table, looked up at runtime. | -| Dynamic shape | Falls out of symbolic loop bounds. Per-tile cost is static (tiles are fixed-size); only trip count is dynamic. | - -## 5. Architecture - -### 5.1 Artifacts (per kernel) - -- **Trace `.so`** — compiled from the skeleton MLIR. Shape-parametric: symbolic - bounds become C++ function parameters. -- **Cycle table** — `tile_id -> (cycle, overlapping_cycle)`, a TSV sidecar. - -Both are written next to the kernel's `tile_graph.onnx`. TOGSim picks the `.so` -up automatically; `TORCHSIM_LEGACY_TOG=1` forces the deprecated ONNX path. - -### 5.2 Pipeline - -``` -post-vcix MLIR (affine/scf.for + togsim.transfer/wait + vcix/vector compute) -| -+-- Branch A (trace): -| build_skeleton.py loops kept, bounds as-is (symbolic preserved) -| togsim.transfer -> togsim.dma(..., tag_id, %tag[%idx], is_async) -| togsim.wait -> togsim.memory_barrier(tag_id, %tag[%idx], write_bufs) -| compute body -> togsim.compute(tile_id, dims) -| DCE everything with no path to a loop bound, an -| address, or an API operand -| dep_analysis.py per-op read/write SRAM buffer sets (SSA) + the vcix -| preload/matmul pairing (§10.2) -| lower_to_emitc.py togsim.* -> emitc.call_opaque; drive the upstream -| lower-affine / convert-{scf,arith,func}-to-emitc -| mlir-translate --mlir-to-cpp -> C++ -| g++ -shared -> trace.so -| -+-- Branch B (cost): - cycle_table.py reuse the gem5 sample-mode cycle_list already computed - in triton_backend/timing.py -> tile_id -> (cycle, overlapping) - -TOGSim: - run_producer() dlopen(trace.so), resolve togsim_kernel, inject EmitCtx - { core pool; record sink; cycle table }, run it - -> a TraceRec stream - trace_to_tilegraph() TraceRec -> TileGraph (Instruction DAG, §10) - Simulator / Core cycles, DRAM traffic (unchanged) -``` - -### 5.3 Components - -- **`togsim_ops.py`** — the op vocabulary. The ops are kept *unregistered* (like - the existing `togsim.transfer`), so no C++ dialect registration is needed and - the togsim->emitc step is a Python rewrite rather than a registered - ConversionPass. -- **`build_skeleton.py`** — reduces the kernel to loops + API ops. Preserves - `is_async`; maps `togsim.wait` through to an explicit - `togsim.memory_barrier`. The IR verifies across sibling prefetch/compute loop - nests because the DMA/barrier pairing is by runtime tag slot, not a - cross-region SSA edge. -- **`dep_analysis.py`** — the read/write SRAM buffer sets per op (§10.2). -- **`lower_to_emitc.py`** — rewrites `togsim.*` to `emitc.call_opaque`, outlines - the work-item body (§9.4), then drives the upstream conversion passes. -- **`cycle_table.py`** — the `tile_id -> (cycle, overlapping_cycle)` sidecar. -- **`togsim_runtime.{h,cc}`** — the C ABI and the `EmitCtx` callback - implementations. -- **`togsim_loader.h`** — `run_producer`: `dlopen`, ABI-version check, run, - record. -- **`togsim_trace_bridge.{h,cc}`** — `TraceRec` stream -> `TileGraph`. - -### 5.4 ABI (v12) - -`mlir-translate --mlir-to-cpp` lowers `emitc.call_opaque` to *free function* -calls, so the contract is a set of `extern "C"` functions taking an opaque -`EmitCtx*` first argument. The loaded `.so` links back into the Simulator binary -(built with `ENABLE_EXPORTS`), so the symbols resolve without an explicit -function table. `togsim_abi_version()` guards against a producer built against a -stale header. - -```c -typedef struct EmitCtx EmitCtx; -typedef void (*togsim_tile_fn)(EmitCtx*, int64_t* iv, int32_t n_iv); - -int32_t togsim_abi_version(void); - -void togsim_dma(EmitCtx*, int32_t dir, int32_t arg_id, uint64_t offset, - int32_t ndim, const int64_t* dims, const int64_t* strides, - int32_t elem_bits, int32_t is_async, - int32_t tag_id, uint64_t tag_slot, - const int64_t* read_bufs, int32_t n_read, - const int64_t* write_bufs, int32_t n_write); - -void togsim_compute(EmitCtx*, uint64_t tile_id, int32_t compute_type, - int32_t ndim, const int64_t* dims, - const int64_t* read_bufs, int32_t n_read, - const int64_t* write_bufs, int32_t n_write); - -void togsim_memory_barrier(EmitCtx*, int32_t tag_id, uint64_t tag_slot, - const int64_t* write_bufs, int32_t n_write); - -void togsim_dispatch(EmitCtx*, togsim_tile_fn fn, int64_t* iv, int32_t n_iv); - -// entry point the loader resolves: -void togsim_kernel(EmitCtx*, int64_t* shape_args, int32_t n_shape_args); -``` - -`offset` is an **element** offset within tensor `arg_id`, computed by the -producer from the loop indices; only the runtime knows the tensors' allocation -bases, so it forms `base[arg_id] + offset * elem_bytes`. `compute_type` is -`0` vector / `1` matmul / `2` preload, and routes the op to the VPU or the -systolic array. - -## 6. Compute cost model - -A `togsim.compute(tile_id=...)` says *which* tile to compute, not how long it -takes. Because tiles are fixed-size (`TILE_M/N/K`), each tile's cost is -invariant — only the trip count varies with shape — so it is sampled once and -stored, keyed by `tile_id`. Two numbers per tile, mirroring the legacy TOG: - -- `cycle` — full compute latency, sampled by gem5 sample-mode (the existing - `cycle_list` measurement, reused so both paths stay cycle-consistent). -- `overlapping_cycle` — the portion that overlaps the previous instruction in - the systolic pipeline. The timing core uses it as - `finish = prev.finish + cycle - overlapping`. Derived exactly as the legacy - path does: vector -> `0`, matmul -> `max(cycle - x_offset, 0)`, preload -> - `max(cycle - w_offset, 0)`. - -`togsim_compute` looks both up and sets them on the `Instruction`. - -**Remainder tiles.** When a dimension is not divisible by the tile size, the -edge tile is partial and its true cost differs from the table entry. Today it is -charged the full-tile cost. Sampling a separate `tile_id` for the remainder is -the alternative; see §11. - -## 7. EmitC lowering notes - -`lower_to_emitc` drives the upstream `lower-affine`, `convert-scf-to-emitc`, -`convert-arith-to-emitc` and `convert-func-to-emitc` passes. One gap in this -LLVM 20 build: `convert-scf-to-emitc` emits `emitc.for` with `index` bounds, so -`convert-arith-to-emitc` leaves `builtin.unrealized_conversion_cast` on the -bounds (`emitc.size_t` <-> `index`) that `--reconcile-unrealized-casts` cannot -fold and `mlir-to-cpp` cannot print. - -`_retype_for_to_size_t` therefore retypes each `emitc.for` to `!emitc.size_t` -bounds and induction variable, and folds the residual casts. A `size_t` IV also -makes the lowered *address* arithmetic cast-free, which is what lets each -`togsim_dma` pass a real `(arg_id, element offset)` computed from the loop IVs. - -Unregistered ops (`togsim.*`) have no registered conversion patterns, which is -why the rewrite to `emitc.call_opaque` must be a custom pass and must run before -the upstream conversions. - -## 8. Validation - -The reproduction path for a single kernel: - -```sh -python -m PyTorchSimFrontend.tog.lower_to_emitc \ - --so trace.so [--emit-cpp trace.cpp] -bin/Simulator --config --trace_so trace.so \ - [--cycle_table trace_cycles.tsv] [--log_level trace] -``` - -`--log_level trace` prints the per-instruction issue/finish timeline, which is -how the dependency model is checked: on a 256^3 GEMM the trace shows the -preloads and matmuls pipelining across the systolic arrays, the store waiting -for the last matmul to drain, and each compute waiting for its async weight -load's *data arrival* rather than its issue. Compute work and DRAM traffic match -the legacy path on the same gem5 cycle table. - -## 9. Parallelism, reduction, and core dispatch - -### 9.1 Where the semantics come from - -Nothing has to be inferred. The post-vcix `affine.for` already carries the -mapping decision the frontend made, and `build_skeleton` preserves it: - -| attribute | meaning | role | -|---|---|---| -| `outer_loop` | PARALLEL axis (e.g. GEMM m, n) | independent output tiles -> distributable across cores | -| `accumulation_loop` | REDUCTION axis (e.g. GEMM k) | partial sums into one output tile -> ordered dependency | -| `inner_loop` | tile micro-loop | within one tile | - -### 9.2 Principle: bake intrinsic, parameterize extrinsic - -Two kinds of hardware dependence must be treated differently: - -- **Intrinsic** (vector lanes, `TILE_M/N/K`, systolic size) — defines the - *content and cost of each instruction*. Already baked into the IR. -- **Extrinsic** (`num_cores`) — defines only the *distribution* of an otherwise - fixed set of work-items. The tile set, the cost table, and the DMA tile shapes - are all `num_cores`-invariant. - -So `num_cores` is **not** baked into the producer. The producer is -**core-count transparent**: it never names a core or a core count. - -### 9.3 Core-transparent work function + dispatch hook - -The producer is two functions, split at the PARALLEL/ACCUMULATION boundary: - -```c -// WORK: the trace for ONE independent output tile. Takes the PARALLEL indices; -// names no core. Reduction (k) is program order -- the accumulator is -// core-local, so the ordering is implicit. -static void togsim_kernel_tile(EmitCtx* ctx, int64_t* iv, int32_t n_iv) { - int64_t mi = iv[0], ni = iv[1]; - togsim_compute(ctx, /*tile_id=*/0, ...); // acc init - for (size_t ki = 0; ki < KT; ++ki) { // REDUCTION - togsim_dma(ctx, LOAD, A, offA(mi,ki), ..., /*is_async=*/1, /*tag_id=*/0, ki%D, ...); - togsim_dma(ctx, LOAD, B, offB(ki,ni), ..., /*is_async=*/1, /*tag_id=*/1, ki%D, ...); - togsim_memory_barrier(ctx, 1, ki%D, ...); togsim_compute(ctx, 1, ...); // preload - togsim_memory_barrier(ctx, 0, ki%D, ...); togsim_compute(ctx, 2, ...); // matmul - } - togsim_dma(ctx, STORE, C, offC(mi,ni), ...); -} - -// DISPATCH: enumerate the PARALLEL domain, one work-item per call. -extern "C" void togsim_kernel(EmitCtx* ctx, int64_t* shape, int32_t n) { - for (size_t mi = 0; mi < MT; ++mi) - for (size_t ni = 0; ni < NT; ++ni) { - int64_t iv[2] = {(int64_t)mi, (int64_t)ni}; - togsim_dispatch(ctx, togsim_kernel_tile, iv, 2); - } -} -``` - -Three orthogonal concepts: - -- **Parallel** = each `togsim_dispatch` call is an independent work-item. TOGSim - may place it on any core. -- **Reduction** = ordering *inside* one work-item: program order on its core. -- **Core assignment** = owned by `togsim_dispatch`, whose body lives in TOGSim. - It round-robins a core from the partition's pool and brackets the call with - `TILE_BEGIN`/`TILE_END` records, so the work-item's scope is exactly the - function call. A core is an assignment, not a held resource; there is no free. - -Because `togsim_dispatch` takes the work function as a pointer and forwards an -opaque `iv` array, one general dispatcher serves every kernel. The boundary -cannot be optimized away: TOGSim can only observe `togsim_*` callbacks across -the `dlopen` boundary, never a producer-internal call. - -### 9.4 Codegen and ABI - -`lower_to_emitc` outlines the innermost PARALLEL-loop body into an -`emitc.func togsim_kernel_tile(ctx, iv, n_iv)` and rewrites the dispatcher loop -to call `togsim_dispatch`. The `tile_id -> cycle` table is untouched by all of -this (it is `num_cores`-invariant). - -### 9.5 Stance and the split-K exception - -Refining "not a dynamic scheduler": **the per-work-item trace is static and -deterministic; only the work-item -> core binding is dynamic.** That is -independent-task distribution, not data-dependent control flow. - -The transparent model holds while work-items are independent (data-parallel over -output tiles). **Split-K** — a reduction split *across* cores — breaks -independence: the producer would have to emit `c` partials plus a combine, so -the instruction stream would depend on `num_cores`, and the cross-core -dependency would have to be a real dataflow edge rather than program order. -Split-K is a deliberate, scoped exception, not supported today. - -### 9.6 Work-items form a DAG - -Work-items are not always a flat independent set. A computation *between* -parallel loops can only run once the inner parallel region completes: - -``` -parallel for m: - parallel for n: A(m,n) # leaf work-items, each writes a tile of m's buffer - B(m) # join: reads that buffer -> depends on all n of this m -``` - -This needs **no new primitive**. It is the same dataflow-edge mechanism the -trace already uses (§10), at work-item granularity: the join op declares the -leaves' output buffer as an input, so the bridge makes it depend on every leaf -through the last-writer analysis. - -The general picture: **work-items form a DAG whose edges are buffer -producer -> consumer dependencies.** Independent data-parallel work is the -degenerate edge-less case; barriers, reduction across a parallel axis, and -split-K are the same DAG with real edges. - -### 9.7 Execution model: trace generation, not co-execution - -The producer is a pure trace generator. It never computes cycles, models -hardware, or schedules. Two consequences pin the model: - -- **What is an edge vs. what blocks.** Data dependencies are recorded *edges* — - the producer does not block on them. The only thing that can ever block the - producer is resource backpressure (finite cores, double-buffer slots, DMA - queue depth), which is flow control, not timing semantics. -- **Cores, double-buffering, DRAM and NoC are the timing core's job** — reused, - not reimplemented. The producer stays oblivious; depths and counts are - consumer-side config. - -Consumption is staged behind a swappable **sink**, so the choice touches neither -the producer nor the ABI: - -| sink | threads | when | -|---|---|---| -| *materializing* (today) — callbacks append to a `TraceRec` vector, which the bridge turns into a `TileGraph` | none | static shape | -| *streaming* — callbacks push to a bounded queue; the producer runs as a fiber and blocks on backpressure while the DES loop advances time and resumes it | producer fiber | when dynamic-shape trace size makes full materialization impractical | - -Even the streaming sink only blocks the producer on resource flow control, never -on timing-resolved data events. The single forward-compat requirement is that -the callback sink stays an interface. - -## 10. Dependency model - -The trace is an explicit dataflow DAG: every op declares the buffers it reads -and writes, and the bridge derives edges from that. There is no in-order chain, -no runtime content hash, and no op-pattern heuristic. - -### 10.1 Representation - -Each op carries the **SRAM buffer ids** it reads and writes (`read_bufs` / -`write_bufs`). The bridge maintains `writers(b)`, the set of current producers of -buffer `b`, and links each op against it. Resource scheduling — systolic-array -round-robin, double-buffering, SRAM capacity — stays entirely in the Core; the -trace only states producer -> consumer order. - -### 10.2 Two dependency sources - -A single "SRAM access" analysis is necessary but not sufficient: - -| dependency | source | visible in SRAM? | -|---|---|---| -| load -> compute (a DMA writes X_spad/W_spad; preload/matmul read it) | SRAM last-writer per buffer | yes | -| the accumulator chain (init writes Y_spad; the epilogue read-modify-writes it; the store reads it) | SRAM last-writer on Y_spad | yes | -| **preload -> matmul** (a preload loads weights into the systolic array's registers; the matmul consumes them) | **the vcix opcode FSM** (op1 = preload pairs with the following op0 = matmul) | **no — SA-internal, not a memref access** | - -On the 256^3 GEMM post-vcix, the SRAM buffers are `%0 = X_spad(A)`, -`%1 = W_spad(B)`, `%2 = Y_spad(acc)`. The matmul reads `%0` only; the preload -reads `%1`; the matmul does *not* read `%1`, because the weights come from the -systolic array. That is exactly why a memref-only analysis would let the matmul -run before the weight load. `dep_analysis` closes the gap by folding the -preload -> matmul pairing into a virtual `SA_WEIGHTS` buffer, so the FSM edge -becomes an ordinary last-writer edge. - -Both sources are available *before* `build_skeleton` collapses the compute -bodies, which is why the analysis runs on the post-vcix IR. - -### 10.3 Edge rules - -An instruction has two completion points. A systolic-array op **occupies** its -unit for `cycle - overlapping_cycle` (the initiation interval) and its **result** -is ready at `cycle`. `DepEvent::ISSUE` releases a successor at the former, -`DepEvent::DONE` at the latter. The bridge applies one rule per buffer `b`: - -- **Read `b`** — depend on every instruction in `writers(b)`. The edge is - `ISSUE` when consumer and producer are both systolic-array ops (a matmul - reading a preload or a matmul: they overlap on the pipeline), else `DONE`. -- **Write `b`** — replace: `writers(b) = {inst}`. -- **Exception — the commutative accumulator.** A matmul that both reads and - writes `b` is accumulating (`Y += X @ W`). Skip its read edge, and on the - write *union* rather than replace: it waits only for the non-matmul seed (the - init or bias) and joins `writers(b)` without ordering against its - co-matmuls. So the K matmuls do not chain through the accumulator, and a later - reader joins all of them. - -The last rule is what makes the store wait for the whole reduction while the -matmuls still pipeline: the store reads `Y_spad`, `writers(Y_spad)` is the union -of the K matmuls, and the store is not a systolic-array op, so it takes a `DONE` -edge from each. No explicit compute fence is needed. - -### 10.4 Resource models, not edges - -Write-after-read ordering is *not* expressed as an edge. Buffer reuse is a -resource question, and the Core already models it: - -- **SRAM capacity.** A coarse tile is one *version* of its buffer; the fine DMAs - that fill it share one allocation, freed once all of that version's consumers - have issued. A buffer reused by the next reduction iteration or work-item is a - new version that must wait for the old one to be freed — that is the - double-buffer / WAR constraint, enforced by capacity rather than by ordering - edges, so two versions may physically coexist. -- **Weight slots.** A preload takes a weight slot on a systolic array and holds - it until its matmuls have consumed it, which caps how many preloads can be in - flight per array. - -A latency WAR edge would instead force the new load to wait for the old tile's -readers to *finish*, defeating double-buffering. - -### 10.5 Async DMA: the memory barrier - -An async DMA's own finish is *issue*-complete; its data arrives later, at DMA -response-complete. A raw last-writer edge on the DMA would therefore release a -consumer before the data exists — a real bug this model had to fix. - -So an async load's last-writer edge is routed through its `MEMORY_BAR`. The DMA -registers its tag at issue; the barrier parks on `(tag_id, tag_slot)` in the -Core's existing tag table and is woken by `set_tag_finish` at response-complete; -the barrier then replaces `writers(b)`, so every consumer of the loaded buffer -gates on arrival. A synchronous DMA blocks to arrival itself and needs no -barrier. - -The bridge mints a per-record unique key so that successive reduction iterations -of one static DMA op get distinct tag-table keys, and the matching barrier reuses -that key. This works because the recorded stream is already per-iteration — the -producer ran the loops. - -## 11. Limitations and open work - -- **Per-iteration tags are reconstructed in the bridge.** `dma_fine_grained` - emits a fresh tag `memref.alloc` before each coarse load, but `build_skeleton` - DCEs it and keys `togsim.dma` by the alloc's static identity, so the bridge has - to re-derive per-iteration keys from record order. Threading the alloc identity - through as an SSA tag handle would remove that. -- **Preload occupancy.** A preload's `overlapping_cycle` equals its `cycle`, so - its occupancy is zero and concurrent preloads are not capped by the - systolic-array count. Giving the preload a non-zero occupancy (the weight-load - time) is a cycle-model input, not an edge-model change. This predates the trace - pipeline and affects the legacy path equally. -- **Dispatch granularity.** Work-items are enumerated per innermost parallel - loop. Distributing independent output sub-tiles across cores needs the sub-tile - axis roles, which the inner loops do not currently carry. -- **Remainder tiles** are charged the full-tile cost (§6). -- **Op coverage.** The dependency model has been characterized in detail on - GEMM. Other families go through the same rules but have not been - cycle-characterized. -- **Dynamic shape.** Symbolic bounds survive the pipeline, but end-to-end - `shape_args` plumbing and the streaming sink (§9.7) are not done. -- **Legacy path.** The ONNX TOG producer is deprecated and opt-in - (`TORCHSIM_LEGACY_TOG=1`). It is retired once the trace path is stable across - all op families. The cycle measurement (`cycle_list`, `x_offset`/`w_offset`) is - shared, so both paths stay cycle-consistent meanwhile. - -## Appendix A: legacy-path references - -- `TOGSim/include/DMA.h` — `tag_table` (overloaded `0/1/-1/>1`) + `waiters`; - `register_tag` / `set_tag_finish` / `register_tag_waiter` / `mark_tag_used` - (= init / signal / wait / consume). -- `TOGSim/src/Core.cc` — the async-DMA signal path and the barrier wait/consume - path over the tag table. -- `TOGSim/include/Instruction.h` — `ready_counter` / dependency edges and the tag - fields. -- `PyTorchSimFrontend/tog/build_tog.py` — `TogBuilder.print_operation` - dispatch and `_affine_for_bounds` (constant-bound resolution -> static shape). -- `AsmParser/tog_generator.py` — the ONNX serialization. -- `PyTorchSimFrontend/triton_backend/inductor_templates.py` — the mm/bmm tiles emitting - the `affine.for` nest, `linalg.matmul`, and the `togsim.transfer` DMA ops.