Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/pytorchsim_test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
6 changes: 3 additions & 3 deletions TOGSim/include/SimulationConfig.h
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
11 changes: 11 additions & 0 deletions TOGSim/include/Simulator.h
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#pragma once

#include <map>
#include <queue>
#include <filesystem>
#include <string>
Expand Down Expand Up @@ -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; }
Expand All @@ -79,6 +89,7 @@ class Simulator {
// Components
std::vector<std::unique_ptr<Core>> _cores;
std::unique_ptr<UnitTable> _unit_table;
std::map<std::string, int64_t> _kernel_unit_base;
std::unique_ptr<Interconnect> _icnt;
std::unique_ptr<Dram> _dram;
std::vector<std::unique_ptr<Scheduler>> _partition_scheduler;
Expand Down
4 changes: 4 additions & 0 deletions TOGSim/include/UnitTable.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ class UnitTable {

// Parse and validate `path`; on any error, log the offending line and exit(1).
static std::unique_ptr<UnitTable> 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; }
Expand Down Expand Up @@ -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<Unit> _units; // in first-seen order
int64_t _array_unit = -1;
std::vector<std::vector<std::pair<size_t, uint64_t>>> _rows; // tile_id -> (unit, admitted)
Expand Down
3 changes: 2 additions & 1 deletion TOGSim/include/togsim_trace_bridge.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,5 @@ std::unique_ptr<TileGraph> 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<std::shared_ptr<const TensorTiling>>& tilings = {});
const std::vector<std::shared_ptr<const TensorTiling>>& tilings = {},
int64_t unit_tile_base = 0); // added to each compute's tile_id: its rows in a table several kernels share
3 changes: 2 additions & 1 deletion TOGSim/src/Common.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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<uint32_t>();
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<std::string>(config, "dram_type");
Expand Down
19 changes: 14 additions & 5 deletions TOGSim/src/UnitTable.cc
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,21 @@ bool parse_u64(const std::string& s, uint64_t& out) {
} // namespace

std::unique_ptr<UnitTable> UnitTable::load(const std::string& path) {
auto table = std::make_unique<UnitTable>();
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<UnitTable>();
std::map<std::string, std::pair<size_t, size_t>> index;
UnitTable* table = this;
const size_t base = _rows.size();
std::map<std::string, std::pair<size_t, size_t>> 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<std::pair<uint64_t, size_t>> tile_unit;
std::string line;
size_t lineno = 0;
Expand All @@ -56,6 +64,7 @@ std::unique_ptr<UnitTable> 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 {
Expand All @@ -67,10 +76,10 @@ std::unique_ptr<UnitTable> 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 {
Expand Down
21 changes: 16 additions & 5 deletions TOGSim/src/main.cc
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ std::vector<uint64_t> trace_tensor_bases(const fs::path& dir, const std::vector<
std::unique_ptr<TileGraph> 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<int>() : 1;
std::vector<int32_t> partition_cores;
Expand Down Expand Up @@ -110,7 +110,8 @@ std::unique_ptr<TileGraph> 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<std::shared_ptr<const TensorTiling>>(tilings.begin(), tilings.end()));
std::vector<std::shared_ptr<const TensorTiling>>(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) {
Expand All @@ -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<TileGraph> 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;
Expand Down Expand Up @@ -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 {
Expand All @@ -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);
}

Expand Down
5 changes: 4 additions & 1 deletion TOGSim/src/togsim_trace_bridge.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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<int64_t, size_t> buf_bytes;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -458,9 +460,10 @@ std::unique_ptr<TileGraph> 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<std::shared_ptr<const TensorTiling>>& tilings) {
const std::vector<std::shared_ptr<const TensorTiling>>& tilings, int64_t unit_tile_base) {
using togsim::TraceRec;
auto S = std::make_shared<BuildState>();
S->unit_tile_base = unit_tile_base;
S->indirect_dir = indirect_dir;
S->tilings = tilings;

Expand Down
8 changes: 5 additions & 3 deletions TOGSim/tests/core_serial/run_core_serial.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion pytorchsim/driver/autotune.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
2 changes: 1 addition & 1 deletion pytorchsim/driver/codecache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
41 changes: 41 additions & 0 deletions pytorchsim/frontend/rewrite_fx_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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))
Loading