diff --git a/.github/workflows/pytorchsim_test.yml b/.github/workflows/pytorchsim_test.yml index abf735f0a..db6a138b2 100644 --- a/.github/workflows/pytorchsim_test.yml +++ b/.github/workflows/pytorchsim_test.yml @@ -64,6 +64,7 @@ jobs: - tests/ops/fusion/test_matmul_scalar.py - tests/ops/fusion/test_matmul_vector.py - tests/ops/fusion/test_prologue_fusion.py + - tests/ops/gemm/test_row_matmul.py - tests/ops/misc/test_complex_to_real.py - tests/ops/misc/test_eager_to_compile_recursion.py - tests/ops/misc/test_expert_mask.py @@ -75,6 +76,7 @@ jobs: - tests/ops/view/test_view3D_2D.py - tests/system/test_eager.py - tests/system/test_patch_scope.py + - tests/system/test_togsim_result.py steps: - name: Log in to GitHub Container Registry uses: docker/login-action@v3 diff --git a/TOGSim/include/SimulationConfig.h b/TOGSim/include/SimulationConfig.h index 46515ddf9..2d778bc51 100644 --- a/TOGSim/include/SimulationConfig.h +++ b/TOGSim/include/SimulationConfig.h @@ -32,9 +32,9 @@ struct SimulationConfig { // preload stalls until a slot frees (its matmuls finished). 2 = weight // double-buffer (convention default, tunable). 0 = disabled. uint32_t sa_weight_buffer_depth = 2; - // systolic_array_split: round_robin -- a compute's array-unit rows spread over - // min(N, ceil(rows / vpu_num_lanes)) arrays (needs --unit_table); none (default) ignores N. - bool systolic_array_split = false; + // systolic_array_split: round_robin (default) -- a compute's array-unit rows spread over + // min(N, ceil(rows / vpu_num_lanes)) arrays (needs --unit_table); none ignores N. + bool systolic_array_split = true; // systolic_array_unit: the unit table's array unit, Systolic or its variant Msa (one per machine). // The default is the only place TOGSim names a unit: gem5's tpu model calls its array Systolic. std::string systolic_array_unit = "Systolic"; diff --git a/TOGSim/include/Simulator.h b/TOGSim/include/Simulator.h index 260fae390..c83553008 100644 --- a/TOGSim/include/Simulator.h +++ b/TOGSim/include/Simulator.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -53,6 +54,15 @@ class Simulator { } for (auto& core : _cores) core->set_unit_table(_unit_table.get()); } + // A launched kernel's trace_units.tsv joins the one table: the tile_id shift its computes carry. + int64_t add_kernel_unit_table(const std::string& path) { + auto it = _kernel_unit_base.find(path); + if (it != _kernel_unit_base.end()) return it->second; + int64_t base = 0; + if (!_unit_table) set_unit_table(UnitTable::load(path)); + else base = (int64_t)_unit_table->append(path); + return _kernel_unit_base[path] = base; + } void cycle(); const SimulationConfig& get_config() const { return _config; } const YAML::Node& get_hardware_config_yaml() const { return _hardware_config_yaml; } @@ -79,6 +89,7 @@ class Simulator { // Components std::vector> _cores; std::unique_ptr _unit_table; + std::map _kernel_unit_base; std::unique_ptr _icnt; std::unique_ptr _dram; std::vector> _partition_scheduler; diff --git a/TOGSim/include/UnitTable.h b/TOGSim/include/UnitTable.h index 912d1fbb3..db0ebb5fb 100644 --- a/TOGSim/include/UnitTable.h +++ b/TOGSim/include/UnitTable.h @@ -18,6 +18,9 @@ class UnitTable { // Parse and validate `path`; on any error, log the offending line and exit(1). static std::unique_ptr load(const std::string& path); + // The rows of another producer's table `path`, its tile_ids shifted behind the ones held: returns + // that shift. A unit the table does not have yet is an error (one machine, one set of units). + size_t append(const std::string& path) { return read(path, false); } size_t num_units() const { return _units.size(); } const std::string& unit_name(size_t u) const { return _units[u].name; } @@ -59,6 +62,7 @@ class UnitTable { bool print_spread(const std::string& who, size_t u, double admitted, uint64_t cycles) const; private: + size_t read(const std::string& path, bool new_units); std::vector _units; // in first-seen order int64_t _array_unit = -1; std::vector>> _rows; // tile_id -> (unit, admitted) diff --git a/TOGSim/include/togsim_trace_bridge.h b/TOGSim/include/togsim_trace_bridge.h index f006fc1b0..2d4ea9f73 100644 --- a/TOGSim/include/togsim_trace_bridge.h +++ b/TOGSim/include/togsim_trace_bridge.h @@ -22,4 +22,5 @@ std::unique_ptr trace_to_tilegraph( const int64_t* cyc, const int64_t* ovl, int32_t n_tiles, const int32_t* partition_cores, int32_t n_partition_cores, const std::string& indirect_dir, const std::string& name, - const std::vector>& tilings = {}); + const std::vector>& tilings = {}, + int64_t unit_tile_base = 0); // added to each compute's tile_id: its rows in a table several kernels share diff --git a/TOGSim/src/Common.cc b/TOGSim/src/Common.cc index 5844e1d84..8a35d5605 100644 --- a/TOGSim/src/Common.cc +++ b/TOGSim/src/Common.cc @@ -82,7 +82,8 @@ SimulationConfig initialize_config(const YAML::Node& config, if (config["vpu_num_lanes"]) parsed_config.vpu_num_lanes = config["vpu_num_lanes"].as(); if (parsed_config.systolic_array_split && parsed_config.vpu_num_lanes == 0) - throw std::runtime_error("systolic_array_split: round_robin needs vpu_num_lanes"); + throw std::runtime_error("systolic_array_split: round_robin (the default) needs vpu_num_lanes; " + "systolic_array_split: none runs without it"); /* DRAM config */ std::string dram_type_str = get_config_value(config, "dram_type"); diff --git a/TOGSim/src/UnitTable.cc b/TOGSim/src/UnitTable.cc index a88159c85..f12dbe420 100644 --- a/TOGSim/src/UnitTable.cc +++ b/TOGSim/src/UnitTable.cc @@ -25,13 +25,21 @@ bool parse_u64(const std::string& s, uint64_t& out) { } // namespace std::unique_ptr UnitTable::load(const std::string& path) { + auto table = std::make_unique(); + table->read(path, true); + return table; +} + +size_t UnitTable::read(const std::string& path, bool new_units) { std::ifstream in(path); if (!in.is_open()) { spdlog::error("[TOGSim] --unit_table {}: cannot open", path); exit(EXIT_FAILURE); } - auto table = std::make_unique(); - std::map> index; + UnitTable* table = this; + const size_t base = _rows.size(); + std::map> index; // unit -> (its index, the line that named it; 0 = held) + for (size_t u = 0; u < _units.size(); u++) index.emplace(_units[u].name, std::make_pair(u, (size_t)0)); std::set> tile_unit; std::string line; size_t lineno = 0; @@ -56,6 +64,7 @@ std::unique_ptr UnitTable::load(const std::string& path) { if (!parse_u64(f[4], admitted)) reject(path, lineno, fmt::format("admitted '{}' is not a non-negative integer", f[4])); auto it = index.find(f[1]); if (it == index.end()) { + if (!new_units) reject(path, lineno, fmt::format("unit {} is not one the first kernel's table has", f[1])); it = index.emplace(f[1], std::make_pair(table->_units.size(), lineno)).first; table->_units.push_back({f[1], f[2], capacity}); } else { @@ -67,10 +76,10 @@ std::unique_ptr UnitTable::load(const std::string& path) { const size_t u = it->second.first; if (!tile_unit.emplace(tile, u).second) reject(path, lineno, fmt::format("second row for tile {} unit {}", tile, f[1])); - if (tile >= table->_rows.size()) table->_rows.resize(tile + 1); - table->_rows[tile].emplace_back(u, admitted); + if (base + tile >= table->_rows.size()) table->_rows.resize(base + tile + 1); + table->_rows[base + tile].emplace_back(u, admitted); } - return table; + return base; } bool UnitTable::print(const std::string& who, size_t u, uint64_t admitted, uint64_t cycles, bool check) const { diff --git a/TOGSim/src/main.cc b/TOGSim/src/main.cc index 50ad5a5d8..d93cc56ce 100644 --- a/TOGSim/src/main.cc +++ b/TOGSim/src/main.cc @@ -76,7 +76,7 @@ std::vector trace_tensor_bases(const fs::path& dir, const std::vector< std::unique_ptr build_trace_tilegraph(Simulator* simulator, const std::string& trace_so_path, const std::string& cycle_table_path, - int partition_id) { + int partition_id, int64_t unit_tile_base = 0) { const auto& cfg = simulator->get_hardware_config_yaml(); int num_cores = cfg["num_cores"] ? cfg["num_cores"].as() : 1; std::vector partition_cores; @@ -110,7 +110,8 @@ std::unique_ptr build_trace_tilegraph(Simulator* simulator, partition_cores.data(), (int32_t)partition_cores.size(), (fs::path(trace_so_path).parent_path() / "runtime" / "indirect_access").string(), "trace_kernel", - std::vector>(tilings.begin(), tilings.end())); + std::vector>(tilings.begin(), tilings.end()), + unit_tile_base); } 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) { @@ -120,8 +121,16 @@ void launchKernel(Simulator* simulator, unsigned int kernel_id, std::string onnx std::string cycle_tsv = dir + "/trace_cycles.tsv"; if (!fs::exists(trace_so)) throw std::runtime_error("[TOGSim] no trace.so next to " + onnx_path); + // Its unit table, when gem5 left one beside it, joins the simulator's: systolic_array_split reads it. + std::string units_tsv = dir + "/trace_units.tsv"; + int64_t unit_tile_base = 0; + if (fs::exists(units_tsv)) + unit_tile_base = simulator->add_kernel_unit_table(units_tsv); + else if (simulator->get_config().systolic_array_split) + throw std::runtime_error("[TOGSim] systolic_array_split (on by default) reads each tile's Systolic rows; no " + "trace_units.tsv next to " + onnx_path + " (or set systolic_array_split: none)"); std::unique_ptr tile_graph = - build_trace_tilegraph(simulator, trace_so, cycle_tsv, partition_id); + build_trace_tilegraph(simulator, trace_so, cycle_tsv, partition_id, unit_tile_base); if (!tile_graph) throw std::runtime_error("[TOGSim] trace.so run failed for " + trace_so); std::string tog_path = trace_so; @@ -279,7 +288,8 @@ int main(int argc, char** argv) { cmd_parser.set_if_defined("unit_table", &unit_table_path); if (!unit_table_path.empty()) simulator->set_unit_table(UnitTable::load(unit_table_path)); if (simulator->get_config().systolic_array_split && unit_table_path.empty()) { - spdlog::error("[TOGSim] systolic_array_split reads each tile's Systolic rows; give --unit_table"); + spdlog::error("[TOGSim] systolic_array_split (on by default) reads each tile's Systolic rows; give " + "--unit_table, or set systolic_array_split: none"); exit(EXIT_FAILURE); } try { @@ -304,7 +314,8 @@ int main(int argc, char** argv) { std::string unit_table_path; cmd_parser.set_if_defined("unit_table", &unit_table_path); if (!unit_table_path.empty()) { - spdlog::error("[TOGSim] --unit_table is keyed by one producer's tile_ids; use it with --trace_so"); + spdlog::error("[TOGSim] --unit_table is keyed by one producer's tile_ids; use it with --trace_so " + "(a launched kernel brings its own trace_units.tsv)"); exit(1); } diff --git a/TOGSim/src/togsim_trace_bridge.cc b/TOGSim/src/togsim_trace_bridge.cc index cd9d4bb2c..d601a651f 100644 --- a/TOGSim/src/togsim_trace_bridge.cc +++ b/TOGSim/src/togsim_trace_bridge.cc @@ -86,6 +86,7 @@ class BufferWriters { // the TileGraph's tile source, so it survives between materializations. link() is // the dependency DAG, sram_effects() the buffer-version rule, feed() the dispatch. struct BuildState { + int64_t unit_tile_base = 0; // see trace_to_tilegraph togsim::LazyProducer prod; size_t next = 0; // next work-item to materialize std::map buf_bytes; @@ -424,6 +425,7 @@ struct BuildState { open_batch.erase(ob); } else if (t.kind == TraceRec::COMPUTE) { auto inst = make_compute(t); + inst->set_tile_id(unit_tile_base + (int64_t)t.tile_id); inst->set_tile_group(cur_tile_group); link(inst, t.read_bufs, t.write_bufs); note_bufs(t.read_bufs); note_bufs(t.write_bufs); // distinct-buffer footprint for 1- vs 2-dispatch @@ -458,9 +460,10 @@ std::unique_ptr trace_to_tilegraph( const int64_t* cyc, const int64_t* ovl, int32_t n_tiles, const int32_t* partition_cores, int32_t n_partition_cores, const std::string& indirect_dir, const std::string& name, - const std::vector>& tilings) { + const std::vector>& tilings, int64_t unit_tile_base) { using togsim::TraceRec; auto S = std::make_shared(); + S->unit_tile_base = unit_tile_base; S->indirect_dir = indirect_dir; S->tilings = tilings; diff --git a/TOGSim/tests/core_serial/run_core_serial.sh b/TOGSim/tests/core_serial/run_core_serial.sh index 1a7263ed7..2081772d0 100755 --- a/TOGSim/tests/core_serial/run_core_serial.sh +++ b/TOGSim/tests/core_serial/run_core_serial.sh @@ -8,8 +8,9 @@ SIM="${1:-$HERE/../../build/bin/Simulator}" INC="${2:-$HERE/../../include}" SRC_CFG="$HERE/../../../configs/systolic_ws_256x256_c1_simple_noc_tpuv6e.yml" OUT="$(mktemp -d)" -sed -e "s#^ramulator_config_path: \.\./#ramulator_config_path: $HERE/../../../#" "$SRC_CFG" > "$OUT/cfg.yml" -{ cat "$OUT/cfg.yml"; echo "systolic_array_split: round_robin"; } > "$OUT/split.yml" +sed -e "s#^ramulator_config_path: \.\./#ramulator_config_path: $HERE/../../../#" "$SRC_CFG" > "$OUT/base.yml" +{ cat "$OUT/base.yml"; echo "systolic_array_split: none"; } > "$OUT/cfg.yml" +cp "$OUT/base.yml" "$OUT/split.yml" sed -e 's/^num_systolic_array_per_core: .*/num_systolic_array_per_core: 4/' "$OUT/split.yml" > "$OUT/split4.yml" { cat "$OUT/cfg.yml"; echo "systolic_array_unit: Msa"; } > "$OUT/msa_nosplit.yml" sed -e 's/^num_cores: 1$/num_cores: 2/' "$OUT/cfg.yml" > "$OUT/c2.yml" @@ -38,6 +39,7 @@ run split_short g1 split.yml "$HERE/cycles_cc1100.tsv" units.tsv run split_no_array g1 split.yml "$HERE/cycles.tsv" units_no_array.tsv run split4_one_over g1 split4.yml "$HERE/cycles_cc230.tsv" units_one_subtile.tsv run msa_nosplit g1 msa_nosplit.yml "$HERE/cycles.tsv" units.tsv +run default_no_table g1 base.yml "$HERE/cycles.tsv" python3 - "$OUT" <<'PY' import re, sys @@ -81,7 +83,7 @@ for name, want in (("split", 1077), ("split_one", 1589), ("split_vpu", 1265), (" mm = sorted({c[4] for c in comps(name) if c[3] == 1}) check(f"K3 {name}: matmul runs {want}", rc(name) == 0 and mm == [want], f"exit {rc(name)}, matmul {mm}") for name, said in (("split_no_array", "has no array unit"), ("msa_nosplit", "is ignored without"), - ("split4_one_over", "Systolic spread")): + ("split4_one_over", "Systolic spread"), ("default_no_table", "give --unit_table")): check(f"K5 {name} refused", rc(name) != 0 and said in log(name), f"exit {rc(name)}") print("FAIL " + "; ".join(bad) if bad else "PASS") sys.exit(1 if bad else 0) diff --git a/pytorchsim/driver/autotune.py b/pytorchsim/driver/autotune.py index f8ab0d77d..67c4a7d19 100644 --- a/pytorchsim/driver/autotune.py +++ b/pytorchsim/driver/autotune.py @@ -107,7 +107,7 @@ def _time_tile(src_code, meta, kernel_name, workdir, timeout): try: compiler_bridge.run_pipeline(spec_path, workdir, to_stage="torchsim-compile", tog=True) timing.emit_trace(workdir, meta) - mine = contract.link_shared(workdir, (timing.TRACE_SO, timing.CYCLE_TSV)) + mine = contract.link_shared(workdir, timing.SHARED) timing.write_shape(workdir, meta) timing.write_tensors(workdir) result = TOGSimulator.run_standalone(os.path.join(mine, "tile_graph.onnx"), diff --git a/pytorchsim/driver/codecache.py b/pytorchsim/driver/codecache.py index 0131b23d7..dbb56ae17 100644 --- a/pytorchsim/driver/codecache.py +++ b/pytorchsim/driver/codecache.py @@ -35,7 +35,7 @@ def _write_path(src_code): STAMP_NAME = "provenance.json" -_STALE_PATTERNS = ("[0-9][0-9]-*", "trace.so", "trace_cycles.tsv", "timing.json") +_STALE_PATTERNS = ("[0-9][0-9]-*", "trace.so", "trace_cycles.tsv", "trace_units.tsv", "timing.json") _identity = None diff --git a/pytorchsim/frontend/rewrite_fx_graph.py b/pytorchsim/frontend/rewrite_fx_graph.py index 836e5989e..f146ff23c 100644 --- a/pytorchsim/frontend/rewrite_fx_graph.py +++ b/pytorchsim/frontend/rewrite_fx_graph.py @@ -245,6 +245,46 @@ def rewrite_topk(g) -> None: _recompile(g) +def _row_times_matrix(node): + """(a, b, bias) of an mm or a plain addmm whose left operand is one row, else None.""" + if node.op != "call_function": + return None + if node.target is aten.mm.default: + (a, b), bias = node.args, None + elif node.target is aten.addmm.default and not node.kwargs: + bias, a, b = node.args + else: + return None + av, bv = _val(a), _val(b) + if av is None or bv is None or av.dim() != 2 or bv.dim() != 2 or av.shape[0] != 1: + return None + return a, b, bias + + +def rewrite_row_mm(g) -> None: + """Replace a 1 x K row times a K x N matrix with the row broadcast down the matrix, a + multiply and a sum over K: vector work, where the mm template would run it on the array.""" + if isinstance(g, fx.GraphModule): + g = g.graph + changed = 0 + for node in list(g.nodes): + found = _row_times_matrix(node) + if found is None: + continue + a, b, bias = found + k = int(_val(a).shape[1]) + with g.inserting_before(node): + column = g.call_function(aten.view.default, (a, [k, 1])) + scaled = g.call_function(aten.mul.Tensor, (column, b)) + out = g.call_function(aten.sum.dim_IntList, (scaled, [0], True)) + if bias is not None: + out = g.call_function(aten.add.Tensor, (out, bias)) + node.replace_all_uses_with(out) + changed += 1 + if changed: + _recompile(g) + + _MUL = (aten.mul.Tensor, aten.mul.Scalar) _SHAPE = (aten.unsqueeze.default,) _HANDLED = (aten.view_as_complex.default,) + _MUL + _SHAPE @@ -360,4 +400,5 @@ def install(): """Chain the post-grad passes onto Inductor's hook, each at most once.""" install_once("pytorchsim-grouped-mm", npu_only(rewrite_grouped_mm)) install_once("pytorchsim-topk", npu_only(rewrite_topk)) + install_once("pytorchsim-row-mm", npu_only(rewrite_row_mm)) install_once(_COMPLEX_TO_REAL.uuid(), npu_only(_COMPLEX_TO_REAL)) diff --git a/pytorchsim/simulator/timing.py b/pytorchsim/simulator/timing.py index 483035585..11044145e 100644 --- a/pytorchsim/simulator/timing.py +++ b/pytorchsim/simulator/timing.py @@ -1,7 +1,7 @@ """The timing half of the Triton route: the compiler IR -> trace.so -> TOGSim. run(workdir, meta, args) emit if needed, then simulate, under the lock - emit_trace(workdir, meta) the compiler's trace.so + gem5 cycles -> trace_cycles.tsv + emit_trace(workdir, meta) the compiler's trace.so + gem5 cycles -> trace_cycles.tsv, trace_units.tsv run_togsim(workdir, ...) hand them to TOGSim, return its parsed result """ @@ -20,6 +20,8 @@ TRACE_SO = "trace.so" CYCLE_TSV = "trace_cycles.tsv" +UNITS_TSV = "trace_units.tsv" +SHARED = (TRACE_SO, CYCLE_TSV, UNITS_TSV) SHAPE_TXT = "trace_shape.txt" TENSORS_TXT = "trace_tensors.txt" TENSOR_SHAPES_TXT = "trace_tensor_shapes.txt" @@ -154,6 +156,9 @@ def emit_trace(workdir, meta): with open(os.path.join(workdir, AXES_TXT), "w") as f: f.write(f"{len(axes)}\n") + rows = unit_rows(os.path.join(os.path.dirname(contract.artifact(workdir, "cycle_elf")), "m5out")) + with open(os.path.join(workdir, UNITS_TSV), "w") as f: + f.write("".join("\t".join(str(v) for v in r) + "\n" for r in rows)) dump_cycle_table_tsv(table, os.path.join(workdir, CYCLE_TSV)) logger.info("[Gem5] tile cycles: %s", table) return n_tiles @@ -169,10 +174,10 @@ def run_togsim(workdir, meta, args=()): from pytorchsim.simulator.togsim import TOGSimulator - for need in (TRACE_SO, CYCLE_TSV): + for need in SHARED: if not os.path.isfile(os.path.join(workdir, need)): raise FileNotFoundError(f"{os.path.join(workdir, need)} not found -- call emit_trace first") - mine = contract.link_shared(workdir, (TRACE_SO, CYCLE_TSV)) + mine = contract.link_shared(workdir, SHARED) write_shape(workdir, meta, args) write_tensors(workdir) @@ -195,9 +200,13 @@ def run(workdir, meta, args=()): from filelock import FileLock kernel = meta["kernel_name"] - if not os.path.isfile(os.path.join(workdir, CYCLE_TSV)): + + def emitted(): + return all(os.path.isfile(os.path.join(workdir, name)) for name in (CYCLE_TSV, UNITS_TSV)) + + if not emitted(): with FileLock(os.path.join(workdir, LOCK_NAME), timeout=LOCK_TIMEOUT): - if not os.path.isfile(os.path.join(workdir, CYCLE_TSV)): + if not emitted(): with wallclock.span(wallclock.TOGSIM_TRACE, kernel): emit_trace(workdir, meta) with wallclock.span(wallclock.TOGSIM_RUN, kernel): @@ -265,6 +274,52 @@ def compile_and_simulate(self, target_binary, vectorlane_size, silent_mode=False return cycle_list +_ISSUE = "Issue" +_COMMITTED = "system.cpu.commitStats0.numOps" +_CPU_UNITS = "system.cpu.units." + + +def unit_rows(m5out): + """TOGSim's --unit_table rows of a gem5 run, one per sampled tile and unit: (tile_id, unit, + unit_of_work, capacity per cycle, admitted). Issue is the committed micro-ops over the issue + width; the end-of-run dump is left out, as the cycles leave it out.""" + import json + + with open(os.path.join(m5out, "config.json")) as f: + width = int(json.load(f)["system"]["cpu"]["executeIssueLimit"]) + with open(os.path.join(m5out, "stats.txt")) as f: + dumps = f.read().split("Begin Simulation Statistics")[1:-1] + rows = [] + for tile, dump in enumerate(dumps): + units = {} + for line in dump.splitlines(): + field = line.split() + if len(field) < 2 or line[0].isspace(): + continue + name = field[0] + if name == _COMMITTED: + units[_ISSUE] = {"admitted": field[1], "capacity": width, "work": "micro-ops"} + elif name.startswith(_CPU_UNITS): + part = name[len(_CPU_UNITS):].split(".") + elif ".vcix." in name: + part = name.split(".vcix.", 1)[1].split(".") + else: + continue + if name == _COMMITTED or len(part) != 2 or part[1] not in ("admitted", "capacity"): + continue + unit = units.setdefault(part[0], {}) + unit[part[1]] = field[1] + if part[1] == "admitted": + unit["work"] = line.split("#", 1)[1].split()[0] + if _ISSUE not in units: + raise ValueError(f"{m5out}/stats.txt: dump {tile} has no {_COMMITTED}") + for name, u in units.items(): + if "admitted" not in u or "capacity" not in u: + raise ValueError(f"{m5out}/stats.txt: dump {tile}, unit {name} lacks admitted or capacity") + rows.append((tile, name, u["work"], int(u["capacity"]), int(u["admitted"]))) + return rows + + def cycle_table(overlap_offsets, cycle_list): """[(cycle, overlapping_cycle), ...] indexed by tile_id. The compiler states each tile's overlap offset (None where nothing of it overlaps); gem5 gives the cycles.""" diff --git a/pytorchsim/simulator/togsim.py b/pytorchsim/simulator/togsim.py index c8c9d6fab..d57dd8bc6 100644 --- a/pytorchsim/simulator/togsim.py +++ b/pytorchsim/simulator/togsim.py @@ -331,7 +331,8 @@ def run_standalone( 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) - cmd = f"{base_cmd} --trace_so {trace_so} --cycle_table {cycle_tsv}" + unit_tsv = os.path.join(os.path.dirname(str(model_path)), "trace_units.tsv") + cmd = f"{base_cmd} --trace_so {trace_so} --cycle_table {cycle_tsv} --unit_table {unit_tsv}" if config.CONFIG_TOGSIM_DEBUG_LEVEL: cmd += f" --log_level {config.CONFIG_TOGSIM_DEBUG_LEVEL}" @@ -369,64 +370,74 @@ def run_standalone( logger.info(f'[TOGSim] Simulation log{model_path_log}is stored to "{result_path}"') return result_path + _UNIT_LINE = re.compile(r"\] (Core \[\d+\]|Total) : (.+?) [Uu]tilization\(%\): (\d+\.?\d*), " + r"active[ _]cycles?: (\d+), idle[ _]cycles?: (\d+)") + _DRAM_CHANNEL = re.compile(r"\[DRAM\] channel (\d+) \| .*?(\d+\.?\d*)% of utilization") + _DRAM_COMBINED = re.compile(r"\[DRAM\] channels .* combined \| .*?(\d+\.?\d*)% of utilization") + _ARRAY_UNITS = ("Systolic", "Msa") + @staticmethod def get_result_from_file(result_path): + """(core_metrics, dram_channel_bw, avg_dram_bw, simulation_time, total_cycle) of a run's log. + core_metrics["units"] holds every 'Core [i]' and 'Total' unit row; the flat keys read the + array and the vector unit off the Total row, else the one core.""" core_metrics = {} dram_channel_bw = {} avg_dram_bw = 0.0 simulation_time = float("inf") total_cycle = float("inf") - # Read and find total stat position with open(result_path, "r") as f: lines = f.readlines() - simulation_finished_idx = -1 - simulation_finished = False for idx, line in enumerate(lines): if TOGSimulator.FINISH_STR in line: - simulation_finished = True - simulation_finished_idx = idx break - - if simulation_finished_idx == -1: + else: logger.warning(f"[TOGSim] Warning: Unable to parse the output file ({result_path}). The file may be improperly formatted.") - return core_metrics, dram_channel_bw, avg_dram_bw, simulation_time - - total_stat_lines = lines[simulation_finished_idx:] - - for line in total_stat_lines: - # Parse core metrics (MatMul active cycle, Vector active cycle, etc.) - if 'Core' in line: - if 'MatMul active cycle' in line: - matmul_cycle = re.search(r'MatMul active cycle (\d+)', line).group(1) - vector_cycle = re.search(r'Vector active cycle (\d+)', line).group(1) - core_metrics['MatMul_active_cycle'] = int(matmul_cycle) - core_metrics['Vector_active_cycle'] = int(vector_cycle) - elif 'Systolic Array Utilization' in line: - systolic_util = re.search(r'Systolic Array Utilization\(%\) (\d+\.?\d*)', line).group(1) - vector_util = re.search(r'Vector Unit Utilization\(%\) (\d+\.?\d*)', line).group(1) - total_cycle = re.search(r'Total cycle: (\d+)', line).group(1) - core_metrics['Systolic_Array_Utilization'] = float(systolic_util) - core_metrics['Vector_Unit_Utilization'] = float(vector_util) - core_metrics['Total_cycle'] = int(total_cycle) - - # Parse DRAM channel bandwidth utilization - if 'DRAM CH' in line: - channel = re.search(r'DRAM CH\[(\d+)\]', line).group(1) - bw_util = re.search(r'AVG BW Util (\d+\.?\d*)%', line).group(1) - dram_channel_bw[f'CH[{channel}]'] = float(bw_util) - - # Parse average DRAM bandwidth - if 'DRAM: AVG BW Util' in line: - avg_dram_bw = float(re.search(r'AVG BW Util (\d+\.?\d*)%', line).group(1)) - - if 'Total execution cycles' in line: + return core_metrics, dram_channel_bw, avg_dram_bw, simulation_time, total_cycle + + units = {} + combined = None + for line in lines[idx:]: + m = TOGSimulator._UNIT_LINE.search(line) + if m: + units.setdefault(m.group(1), {})[m.group(2)] = { + "utilization": float(m.group(3)), "active_cycles": int(m.group(4)), + "idle_cycles": int(m.group(5))} + continue + m = TOGSimulator._DRAM_CHANNEL.search(line) + if m: + dram_channel_bw[f"CH[{m.group(1)}]"] = float(m.group(2)) + continue + m = TOGSimulator._DRAM_COMBINED.search(line) + if m: + combined = float(m.group(1)) + elif 'Total execution cycles' in line: total_cycle = int(re.search(r'Total execution cycles: (\d+)', line).group(1)) - - # Parse total simulation time - if 'Wall-clock time for simulation' in line: + elif 'Wall-clock time for simulation' in line: simulation_time = float(re.search(r'Wall-clock time for simulation: (\d+\.?\d*) seconds', line).group(1)) + + if combined is not None: + avg_dram_bw = combined + elif dram_channel_bw: + avg_dram_bw = sum(dram_channel_bw.values()) / len(dram_channel_bw) + + if units: + core_metrics["units"] = units + whole = units.get("Total") or next(iter(units.values())) + table = [whole[name] for name in TOGSimulator._ARRAY_UNITS if name in whole] + arrays = ([max(table, key=lambda u: u["active_cycles"])] if table else + [u for name, u in whole.items() if name.startswith("Systolic array [")]) + vector = whole.get("Vpu") or whole.get("Vector unit") + if arrays: + core_metrics["Systolic_Array_Utilization"] = sum(u["utilization"] for u in arrays) / len(arrays) + core_metrics["MatMul_active_cycle"] = sum(u["active_cycles"] for u in arrays) + if vector: + core_metrics["Vector_Unit_Utilization"] = vector["utilization"] + core_metrics["Vector_active_cycle"] = vector["active_cycles"] + if total_cycle != float("inf"): + core_metrics["Total_cycle"] = total_cycle return core_metrics, dram_channel_bw, avg_dram_bw, simulation_time, total_cycle diff --git a/scripts/ci/triton_route_passing.txt b/scripts/ci/triton_route_passing.txt index 10e3d1431..00c5d94c3 100644 --- a/scripts/ci/triton_route_passing.txt +++ b/scripts/ci/triton_route_passing.txt @@ -254,6 +254,7 @@ tests/ops/fusion/test_addmm_residual.py tests/ops/fusion/test_matmul_scalar.py tests/ops/fusion/test_matmul_vector.py tests/ops/fusion/test_prologue_fusion.py +tests/ops/gemm/test_row_matmul.py tests/ops/misc/test_complex_to_real.py tests/ops/misc/test_eager_to_compile_recursion.py tests/ops/misc/test_expert_mask.py @@ -265,3 +266,4 @@ tests/ops/reduce/test_batchnorm.py tests/ops/view/test_view3D_2D.py tests/system/test_eager.py tests/system/test_patch_scope.py +tests/system/test_togsim_result.py diff --git a/scripts/trace_timeline.py b/scripts/trace_timeline.py index 0dce5243d..643956008 100644 --- a/scripts/trace_timeline.py +++ b/scripts/trace_timeline.py @@ -12,7 +12,7 @@ runs from the op's first DRAM response (DRAM_RESP_FIRST, logged by the Core -- so it captures data moving even while still injecting) to its completion (load: data-ready; store: finished), serialized per direction so each is one visible bar (packed row = -saturated bus). A compute slice's width is its occupancy (compute_cycle - overlapping). +saturated bus). A compute slice's width is its compute_cycle, which is what the Core runs it for. Usage: bin/Simulator --config --trace_so --cycle_table --log_level trace \ @@ -111,11 +111,10 @@ def parse(lines): return insts -def _occ(detail): - """(compute_cycle, overlapping_cycle) from a COMP detail string.""" +def _cycles(detail): + """compute_cycle from a COMP detail string.""" cc = re.search(r"compute_cycle=(\d+)", detail) - ov = re.search(r"overlapping_cycle=(\d+)", detail) - return (int(cc.group(1)) if cc else 0, int(ov.group(1)) if ov else 0) + return int(cc.group(1)) if cc else 0 def to_chrome(insts, num_sa=1): @@ -126,9 +125,8 @@ def to_chrome(insts, num_sa=1): vector : COMP type 0 -- 1 VPU. sa : COMP type 1/2 -- each op on the SA the Core reports (`sa=` field; weight-pinned), so lanes auto-split sa0..; rr fallback if absent. - A compute slice's width is compute_cycle - overlapping_cycle (its occupancy = - latency minus the tail that overlaps the next op), starting when the unit - actually picks it up: start = max(issue, unit_free). num_sa>1 -> lanes sa0.. .""" + A compute slice's width is its compute_cycle, starting when the unit actually + picks it up: start = max(issue, unit_free). num_sa>1 -> lanes sa0.. .""" by_core = {} for r in insts.values(): op, detail, core = r["opcode"], r["detail"], r["core"] @@ -177,13 +175,11 @@ def issue_key(r): start = max(r[sk], free) free = max(r[ek], start + 1) add(core, lane, start, free - start, _label(r["opcode"], r["detail"]), r) - # VPU: one server; slice = occupancy (compute_cycle - overlapping_cycle). free = 0 for r in sorted(u["vector"], key=issue_key): if r["issued"] is None: continue - cc, ov = _occ(r["detail"]) - dur = max(cc - ov, 1) + dur = max(_cycles(r["detail"]), 1) start = max(r["issued"], free) free = start + dur add(core, "vector", start, dur, "vector", r) @@ -202,8 +198,7 @@ def _sa_of(r, i): if r["issued"] is None: continue s = _sa_of(r, i) - cc, ov = _occ(r["detail"]) - dur = max(cc - ov, 1) + dur = max(_cycles(r["detail"]), 1) start = max(r["issued"], sa_free[s]) sa_free[s] = start + dur lane = "sa" if max_sa == 1 else f"sa{s}" diff --git a/scripts/util_viewer.py b/scripts/util_viewer.py index 1840eeb4f..507212960 100644 --- a/scripts/util_viewer.py +++ b/scripts/util_viewer.py @@ -30,6 +30,8 @@ r"DRAM BW: ([\d.]+) GB/s \((\d+) responses\)") _VU = re.compile(r"Core \[(\d+)\] : Vector unit [Uu]tilization\(%\): ([\d.]+), " r"active[ _]cycles?: (\d+), idle[ _]cycles?: (\d+)") +_UNIT = re.compile(r"Core \[(\d+)\] : (Systolic|Msa|Vpu) [Uu]tilization\(%\): ([\d.]+), " + r"active_cycles: (\d+), idle_cycles: (\d+)") _TOTCYC = re.compile(r"Core \[(\d+)\] : Total_cycles: (\d+)") _INST = re.compile(r"Core \[(\d+)\] : (\w+) +inst_count: (\d+)" r"(?: \(GEMM: (\d+), Vector: (\d+)(?:, XLU: (\d+))?\))?") @@ -73,7 +75,9 @@ def _core(cores, cid): def parse_log(path): - """Parse one TOGSim info-level log into a run dict, or None if it has no stats.""" + """Parse one TOGSim info-level log into a run dict, or None if it has no stats. A run with the + unit table prints one array row (Systolic or its variant Msa, the other at zero), filed as + array 0, and Vpu as the vector unit; a run without it prints a row per array.""" with open(path, errors="replace") as fh: text = fh.read() if "Total execution cycles" not in text: @@ -114,6 +118,14 @@ def parse_log(path): if m: cur["vu"][int(m.group(1))] = float(m.group(2)) continue + m = _UNIT.search(line) + if m and m.group(2) == "Vpu": + cur["vu"][int(m.group(1))] = float(m.group(3)) + continue + if m: + per = cur["sa"].setdefault(int(m.group(1)), {}) + per[0] = max(per.get(0, 0.0), float(m.group(3))) + continue m = _DMA.search(line) if m: cur["dma"][int(m.group(1))] = { @@ -136,6 +148,12 @@ def parse_log(path): "util": float(m.group(3)), "active": int(m.group(4))} for m in _VU.finditer(tail): _core(run["cores"], m.group(1))["vu"] = {"util": float(m.group(2)), "active": int(m.group(3))} + for m in _UNIT.finditer(tail): + c, row = _core(run["cores"], m.group(1)), {"util": float(m.group(3)), "active": int(m.group(4))} + if m.group(2) == "Vpu": + c["vu"] = row + elif row["active"] >= c["sa"].get(0, row)["active"]: + c["sa"][0] = row for m in _DMA.finditer(tail): _core(run["cores"], m.group(1))["dma"] = { "active": int(m.group(2)), "gbps": float(m.group(4)), "responses": int(m.group(5))} diff --git a/tests/ops/gemm/test_row_matmul.py b/tests/ops/gemm/test_row_matmul.py new file mode 100644 index 000000000..ea17a4501 --- /dev/null +++ b/tests/ops/gemm/test_row_matmul.py @@ -0,0 +1,37 @@ +import os +import sys +import torch +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) +from _pytorchsim_utils import test_result + + +def test_row_matmul(device, hidden_size=256, output_size=384): + """A 1 x K row times a K x N matrix, which the frontend runs as vector work.""" + def row_matmul(a, b): + return torch.matmul(a, b) + torch.manual_seed(0) + row = torch.randn(1, hidden_size) + weight = torch.randn(hidden_size, output_size) + opt_fn = torch.compile(dynamic=False)(row_matmul) + res = opt_fn(row.to(device=device), weight.to(device=device)) + test_result("Row Matmul Forward", res, row_matmul(row, weight)) + + +def test_row_addmm(device, hidden_size=256, output_size=384): + """The same with a bias added, as a Linear layer on one row gives.""" + def row_addmm(bias, a, b): + return torch.addmm(bias, a, b) + torch.manual_seed(0) + row = torch.randn(1, hidden_size) + weight = torch.randn(hidden_size, output_size) + bias = torch.randn(output_size) + opt_fn = torch.compile(dynamic=False)(row_addmm) + res = opt_fn(bias.to(device=device), row.to(device=device), weight.to(device=device)) + test_result("Row Addmm Forward", res, row_addmm(bias, row, weight)) + + +if __name__ == "__main__": + device = torch.device("npu:0") + test_row_matmul(device, 256, 384) + test_row_matmul(device, 61, 56) + test_row_addmm(device, 256, 384) diff --git a/tests/system/data/togsim_arrays.log b/tests/system/data/togsim_arrays.log new file mode 100644 index 000000000..7ab9f631c --- /dev/null +++ b/tests/system/data/togsim_arrays.log @@ -0,0 +1,11 @@ +[2026-10-12 14:12:51.312] [info] Simulation finished +[2026-10-12 14:12:51.313] [info] [DRAM] channel 0 | 11.33 GB/s avg., 22.13% of utilization | 16384 reads, 8192 writes +[2026-10-12 14:12:51.313] [info] [DRAM] channel 1 | 11.33 GB/s avg., 22.13% of utilization | 16384 reads, 8192 writes +[2026-10-12 14:12:51.313] [info] [DRAM] channels 0..31 combined | 362.64 GB/s aggregate, 22.13% of utilization (avg. per channel) | 524288 reads, 262144 writes +[2026-10-12 14:12:51.313] [info] ========= Core stat ========= +[2026-10-12 14:12:51.313] [info] Core [0] : Systolic array [0] utilization(%): 64.06, active_cycles: 142475, idle_cycles: 79940 +[2026-10-12 14:12:51.313] [info] Core [0] : Systolic array [1] utilization(%): 0.00, active_cycles: 0, idle_cycles: 222415 +[2026-10-12 14:12:51.313] [info] Core [0] : Vector unit utilization(%): 2.39, active cycle: 5320, idle_cycle: 0 +[2026-10-12 14:12:51.313] [info] Core [0] : Cross-lane unit utilization(%): 0.00, active cycle: 0, idle_cycle: 222415 +[2026-10-12 14:12:51.313] [info] Core [0] : Total_cycles: 222415 +[2026-10-12 14:12:51.313] [info] Total execution cycles: 222415 diff --git a/tests/system/data/togsim_units.log b/tests/system/data/togsim_units.log new file mode 100644 index 000000000..cc653ba2d --- /dev/null +++ b/tests/system/data/togsim_units.log @@ -0,0 +1,14 @@ +[2026-10-12 15:07:52.975] [info] Simulation finished +[2026-10-12 15:07:52.975] [info] [DRAM] channel 0 | 19.48 GB/s avg., 38.06% of utilization | 16384 reads, 8192 writes +[2026-10-12 15:07:52.975] [info] [DRAM] channel 1 | 19.48 GB/s avg., 38.06% of utilization | 16384 reads, 8192 writes +[2026-10-12 15:07:52.975] [info] [DRAM] channels 0..31 combined | 623.52 GB/s aggregate, 38.06% of utilization (avg. per channel) | 524288 reads, 262144 writes +[2026-10-12 15:07:52.975] [info] ========= Core stat ========= +[2026-10-12 15:07:52.975] [info] Core [0] : Issue utilization(%): 11.70, active_cycles: 15130, idle_cycles: 114227 +[2026-10-12 15:07:52.975] [info] Core [0] : Misc utilization(%): 0.20, active_cycles: 256, idle_cycles: 129101 +[2026-10-12 15:07:52.975] [info] Core [0] : Msa utilization(%): 0.00, active_cycles: 0, idle_cycles: 129357 +[2026-10-12 15:07:52.975] [info] Core [0] : Sfu utilization(%): 0.00, active_cycles: 0, idle_cycles: 129357 +[2026-10-12 15:07:52.975] [info] Core [0] : Systolic utilization(%): 50.66, active_cycles: 65536, idle_cycles: 63821 +[2026-10-12 15:07:52.975] [info] Core [0] : Xlu utilization(%): 0.00, active_cycles: 0, idle_cycles: 129357 +[2026-10-12 15:07:52.975] [info] Core [0] : Vpu utilization(%): 26.39, active_cycles: 34132, idle_cycles: 95225 +[2026-10-12 15:07:52.975] [info] Core [0] : Total_cycles: 129357 +[2026-10-12 15:07:52.975] [info] Total execution cycles: 129357 diff --git a/tests/system/test_togsim_result.py b/tests/system/test_togsim_result.py new file mode 100644 index 000000000..f7fee6463 --- /dev/null +++ b/tests/system/test_togsim_result.py @@ -0,0 +1,50 @@ +"""get_result_from_file reads the statistics TOGSim prints today: one row per unit with the unit +table (the default), a row per array without it. Both logs are cut from real 2048x2048x2048 runs.""" +import os +import sys +import tempfile + +sys.path.insert(0, os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim")) + +from pytorchsim.simulator.togsim import TOGSimulator + +DATA = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data") + + +def test_unit_table_rows(): + core, channels, avg_bw, wall, total = TOGSimulator.get_result_from_file( + os.path.join(DATA, "togsim_units.log")) + units = core["units"]["Core [0]"] + assert units["Systolic"] == {"utilization": 50.66, "active_cycles": 65536, "idle_cycles": 63821} + assert units["Vpu"]["active_cycles"] == 34132 + assert core["Systolic_Array_Utilization"] == 50.66 + assert core["MatMul_active_cycle"] == 65536 + assert core["Vector_Unit_Utilization"] == 26.39 + assert core["Total_cycle"] == total == 129357 + assert channels == {"CH[0]": 38.06, "CH[1]": 38.06} and avg_bw == 38.06 + assert wall == float("inf") + + +def test_per_array_rows(): + core, channels, avg_bw, _, total = TOGSimulator.get_result_from_file( + os.path.join(DATA, "togsim_arrays.log")) + units = core["units"]["Core [0]"] + assert units["Systolic array [0]"]["active_cycles"] == 142475 + assert units["Vector unit"] == {"utilization": 2.39, "active_cycles": 5320, "idle_cycles": 0} + assert core["Systolic_Array_Utilization"] == (64.06 + 0.0) / 2 + assert core["MatMul_active_cycle"] == 142475 + assert total == 222415 and avg_bw == 22.13 and len(channels) == 2 + + +def test_unfinished_log_has_the_same_shape(): + with tempfile.NamedTemporaryFile("w", suffix=".log") as log: + log.write("[info] Core [0] : Total_cycles: 3\n") + log.flush() + assert TOGSimulator.get_result_from_file(log.name) == ({}, {}, 0.0, float("inf"), float("inf")) + + +if __name__ == "__main__": + test_unit_table_rows() + test_per_array_rows() + test_unfinished_log_has_the_same_shape() + print("PASS")