better throughput scheduling with steady state cost model (WIP)
This commit is contained in:
@@ -37,6 +37,13 @@ add_pim_unittest(SpatialSchedulingTargetTest
|
||||
OMPimCompilerUtils
|
||||
)
|
||||
|
||||
add_pim_unittest(PeriodicDependenciesTest
|
||||
PeriodicDependenciesTest.cpp
|
||||
|
||||
LINK_LIBS PRIVATE
|
||||
OMPimCompilerUtils
|
||||
)
|
||||
|
||||
add_test(
|
||||
NAME PimHostReuseSynchronizationTest
|
||||
COMMAND "${PYTHON_EXECUTABLE}"
|
||||
@@ -49,3 +56,24 @@ add_test(NAME PimTargetConfigTest
|
||||
COMMAND "${PYTHON_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/test_PimTargetConfig.py"
|
||||
--compiler "$<TARGET_FILE:onnx-mlir>")
|
||||
set_tests_properties(PimTargetConfigTest PROPERTIES LABELS pim-unittest)
|
||||
|
||||
add_test(NAME PimPeriodicInstructionTest
|
||||
COMMAND "${PYTHON_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/test_PimPeriodicDiagnostic.py"
|
||||
--diagnostic "$<TARGET_FILE:raptor-periodic>")
|
||||
set_tests_properties(PimPeriodicInstructionTest PROPERTIES LABELS pim-unittest)
|
||||
add_dependencies(pim-unittest raptor-periodic)
|
||||
|
||||
add_test(NAME PimQueueSelectionTest
|
||||
COMMAND "${PYTHON_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/test_QueueSelection.py"
|
||||
--compiler "$<TARGET_FILE:onnx-mlir>")
|
||||
set_tests_properties(PimQueueSelectionTest PROPERTIES LABELS pim-unittest)
|
||||
|
||||
add_test(NAME PimEmissionTest
|
||||
COMMAND "${PYTHON_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/test_PimEmission.py"
|
||||
--compiler "$<TARGET_FILE:onnx-mlir>")
|
||||
set_tests_properties(PimEmissionTest PROPERTIES LABELS pim-unittest)
|
||||
|
||||
add_pim_unittest(PimPipelineSelectionTest
|
||||
PimPipelineSelectionTest.cpp
|
||||
LINK_LIBS PRIVATE OMPimCompilerUtils
|
||||
)
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/PeriodicDependencies.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#ifdef NDEBUG
|
||||
#error "Periodic dependency tests require assertions"
|
||||
#endif
|
||||
#include <cmath>
|
||||
#include <functional>
|
||||
#include <random>
|
||||
|
||||
using namespace onnx_mlir::spatial;
|
||||
|
||||
static double enumerateCycles(size_t count,
|
||||
const std::vector<PeriodicDependency> &edges) {
|
||||
double maximum = 0;
|
||||
std::vector<bool> visited(count);
|
||||
for (size_t start = 0; start < count; ++start) {
|
||||
std::function<void(size_t, Cost, Cost)> visit =
|
||||
[&](size_t source, Cost delay, Cost distance) {
|
||||
visited[source] = true;
|
||||
for (const auto &edge : edges) {
|
||||
if (edge.source != source)
|
||||
continue;
|
||||
Cost nextDelay = delay + edge.delayNs;
|
||||
Cost nextDistance = distance + edge.distance;
|
||||
if (edge.target == start && nextDistance)
|
||||
maximum = std::max(maximum,
|
||||
static_cast<double>(nextDelay) / nextDistance);
|
||||
else if (!visited[edge.target])
|
||||
visit(edge.target, nextDelay, nextDistance);
|
||||
}
|
||||
visited[source] = false;
|
||||
};
|
||||
visit(start, 0, 0);
|
||||
}
|
||||
return maximum;
|
||||
}
|
||||
|
||||
static void check(size_t count, const std::vector<PeriodicDependency> &edges,
|
||||
double expected) {
|
||||
std::string error;
|
||||
auto result = analyzePeriodicDependencies(count, edges, error);
|
||||
assert(mlir::succeeded(result) && error.empty());
|
||||
assert(result->recurrenceLowerNs <= expected + 1e-6);
|
||||
assert(result->recurrenceUpperNs >= expected - 1e-6);
|
||||
assert(result->recurrenceUpperNs - result->recurrenceLowerNs <= 1.000001);
|
||||
Cost delay = 0, distance = 0;
|
||||
for (size_t index : result->criticalCycle) {
|
||||
delay += edges[index].delayNs;
|
||||
distance += edges[index].distance;
|
||||
}
|
||||
if (expected > 1) {
|
||||
assert(distance > 0);
|
||||
assert(static_cast<double>(delay) / distance >= result->recurrenceLowerNs - 1e-6);
|
||||
}
|
||||
auto repeated = analyzePeriodicDependencies(count, edges, error);
|
||||
assert(repeated->criticalCycle == result->criticalCycle);
|
||||
assert(repeated->recurrenceUpperNs == result->recurrenceUpperNs);
|
||||
}
|
||||
|
||||
int main() {
|
||||
check(3, {{0, 1, 12, 0}, {1, 2, 7, 0}}, 0);
|
||||
check(3, {{0, 1, 12, 1}, {1, 2, 7, 1}}, 0);
|
||||
check(1, {{0, 0, 30, 2}}, 15);
|
||||
// Independent core periods remain parallel.
|
||||
check(2, {{0, 0, 10, 1}, {1, 1, 20, 1}}, 20);
|
||||
// Equal serial demand, different cross-core blocking recurrences.
|
||||
check(4, {{0, 1, 10, 0}, {2, 3, 10, 0},
|
||||
{1, 0, 0, 1}, {3, 2, 0, 1}}, 10);
|
||||
check(4, {{0, 1, 10, 0}, {2, 3, 10, 0},
|
||||
{1, 2, 0, 0}, {3, 0, 0, 1}}, 20);
|
||||
std::string error;
|
||||
assert(mlir::failed(analyzePeriodicDependencies(
|
||||
2, {{0, 1, 1, 0}, {1, 0, 1, 0}}, error)));
|
||||
assert(mlir::failed(analyzePeriodicDependencies(1, {{0, 1, 1, 1}}, error)));
|
||||
assert(mlir::failed(analyzePeriodicDependencies(
|
||||
1, {{0, 0, Cost{1} << 60, 1}}, error)));
|
||||
std::mt19937 random(812);
|
||||
for (unsigned sample = 0; sample < 300; ++sample) {
|
||||
std::vector<PeriodicDependency> edges;
|
||||
for (size_t source = 0; source < 6; ++source)
|
||||
for (size_t target = 0; target < 6; ++target)
|
||||
if (random() % 4 == 0)
|
||||
edges.push_back({source, target, random() % 101,
|
||||
source < target ? 0u : static_cast<unsigned>(1u + random() % 3)});
|
||||
check(6, edges, enumerateCycles(6, edges));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/ScheduleEvaluation.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/ScheduledSpatialPasses.hpp"
|
||||
#include "llvm/Support/JSON.h"
|
||||
#include <cassert>
|
||||
#include <limits>
|
||||
using namespace onnx_mlir;
|
||||
using namespace onnx_mlir::spatial;
|
||||
int main() {
|
||||
mlir::MLIRContext context;
|
||||
context.allowUnregisteredDialects();
|
||||
mlir::OwningOpRef<mlir::ModuleOp> checkpoint = mlir::ModuleOp::create(mlir::UnknownLoc::get(&context));
|
||||
mlir::OperationState state(checkpoint->getLoc(), "test.compute");
|
||||
auto *op = mlir::Operation::create(state);
|
||||
checkpoint->getBody()->push_back(op);
|
||||
spatial::ComputeInstance instance{op, 3, 2};
|
||||
spatial::MergeScheduleResult schedule;
|
||||
schedule.dominanceOrderCompute.push_back(instance);
|
||||
schedule.computeToCpuMap[instance] = 7;
|
||||
schedule.computeToCpuSlotMap[instance] = 4;
|
||||
schedule.computeToAestMap[instance] = 42;
|
||||
schedule.isLastComputeOfCpu.insert(instance);
|
||||
schedule.cpuToLastComputeMap[7] = instance;
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
mlir::IRMapping mapping;
|
||||
mlir::OwningOpRef<mlir::ModuleOp> trial = mlir::cast<mlir::ModuleOp>((*checkpoint)->clone(mapping));
|
||||
auto remapped = spatial::remapSpatialSchedule(schedule, mapping);
|
||||
auto copy = remapped.dominanceOrderCompute.front();
|
||||
assert(copy.op != op && copy.laneStart == 3 && copy.laneCount == 2);
|
||||
assert(remapped.computeToCpuMap.lookup(copy) == 7 && remapped.computeToCpuSlotMap.lookup(copy) == 4);
|
||||
assert(remapped.computeToAestMap.lookup(copy) == 42 && remapped.isLastComputeOfCpu.contains(copy));
|
||||
assert(remapped.cpuToLastComputeMap.lookup(7) == copy);
|
||||
copy.op->erase();
|
||||
assert(schedule.dominanceOrderCompute.front().op == op && op->getBlock() == checkpoint->getBody());
|
||||
}
|
||||
|
||||
auto score = [](double value, std::string id) { return WholeScheduleCost{value, value, {}, id, 0.021}; };
|
||||
std::string reason;
|
||||
auto original = score(100, "0"), faster = score(90, "1");
|
||||
auto select = [&](std::initializer_list<WholeScheduleCost> values) {
|
||||
return selectPipelineCandidate(llvm::ArrayRef<WholeScheduleCost>(values), reason);
|
||||
};
|
||||
assert(select({original, faster}) == 1);
|
||||
assert(select({original, score(97, "2")}) == 0);
|
||||
assert(select({original, score(105, "2")}) == 0);
|
||||
auto sensitive = faster; sensitive.alternative = 101;
|
||||
assert(select({original, sensitive}) == 0);
|
||||
assert(select({original, faster, score(91, "2")}) == 1);
|
||||
assert(select({original, faster, score(90, "1")}) == 1);
|
||||
auto unavailable = WholeScheduleCost{};
|
||||
assert(select({unavailable, faster}) == 0);
|
||||
assert(select({original, unavailable}) == 0);
|
||||
auto unknownUncertainty = faster;
|
||||
unknownUncertainty.relativeUncertainty.reset();
|
||||
assert(select({original, unknownUncertainty}) == 0);
|
||||
for (double value : {0., -1., std::numeric_limits<double>::infinity(), std::numeric_limits<double>::quiet_NaN()})
|
||||
assert(select({original, score(value, "2")}) == 0);
|
||||
for (int i = 0; i < 8; ++i) assert(select({original, faster}) == 1);
|
||||
|
||||
// The generic query accepts target-lowered IR without a target dialect API.
|
||||
for (double interval : {90., 97.}) {
|
||||
SchedulingTarget target;
|
||||
assert(!target.prepareScheduleCost);
|
||||
target.prepareScheduleCost = [interval](mlir::ModuleOp module,
|
||||
llvm::json::Object &) -> mlir::FailureOr<ScheduleCostQuery> {
|
||||
assert(module.getBody()->getOperations().size() == 1);
|
||||
ScheduleCostQuery query;
|
||||
query.identity = "static-program";
|
||||
query.evaluate = [interval](llvm::json::Object &) {
|
||||
return WholeScheduleCost{interval, interval, {}, "static-program", 0.021};
|
||||
};
|
||||
return query;
|
||||
};
|
||||
llvm::json::Object summary;
|
||||
auto query = target.prepareScheduleCost(*checkpoint, summary);
|
||||
assert(mlir::succeeded(query) && query->identity == "static-program");
|
||||
auto cost = query->evaluate(summary);
|
||||
assert(cost.eligible() && select({original, cost}) == (interval == 90. ? 1 : 0));
|
||||
assert(checkpoint->getBody()->front().getName().getStringRef() == "test.compute");
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,8 @@
|
||||
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/DeferredCommunicationScheduling.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/DeferredBoundaryPlanning.hpp"
|
||||
#include "src/Accelerators/PIM/Compiler/PimScheduleDiagnostic.hpp"
|
||||
#include "src/Accelerators/PIM/Compiler/PimInstructionTiming.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/DeferredTransferPlanning.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/ScheduledComputeMaterialization.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/DeferredCommunicationRealization.hpp"
|
||||
@@ -1030,6 +1032,54 @@ static void checkPublicationMemoryTraffic(mlir::func::FuncOp function,
|
||||
assert(mlir::succeeded(communication));
|
||||
auto boundaries = buildDeferredBoundaryPlan(*shared, *communication, registers);
|
||||
assert(mlir::succeeded(boundaries));
|
||||
std::string before, after;
|
||||
llvm::raw_string_ostream beforeStream(before), afterStream(after);
|
||||
function.print(beforeStream);
|
||||
onnx_mlir::PimInstructionTiming timed;
|
||||
static_cast<SchedulingTarget &>(timed) = target;
|
||||
timed.peerPermissionThenSourceRead = true;
|
||||
timed.signalIssueNs = 1;
|
||||
timed.controlMessageBytes = 1;
|
||||
timed.sharedMemoryRequestLatencyNs.assign(4, 3);
|
||||
timed.sharedMemoryResponseLatencyNs.assign(4, 5);
|
||||
timed.interProcessorLatencyNs.assign(16, 2);
|
||||
for (size_t core = 0; core < 4; ++core)
|
||||
timed.interProcessorLatencyNs[core * 4 + core] = 0;
|
||||
auto report = getPeriodicScheduleReport(graph, *materialized, *shared, *boundaries, timed);
|
||||
assert(report.getString("status") == "estimated");
|
||||
assert(report.getBoolean("diagnostic_only") == true);
|
||||
assert(report.getInteger("boundary_write_bytes") == expected.writeBytes);
|
||||
assert(report.getInteger("boundary_read_bytes") == expected.readBytes);
|
||||
timed.sharedMemoryReadReturnsPayload = false;
|
||||
auto noResponse = getPeriodicScheduleReport(graph, *materialized, *shared, *boundaries, timed);
|
||||
assert(noResponse.getString("status") == "estimated");
|
||||
assert(*noResponse.getNumber("interval_estimate_ns") <= *report.getNumber("interval_estimate_ns"));
|
||||
bool checkedRunOwnership = false;
|
||||
for (size_t i = 0; i < shared->scheduled.size(); ++i)
|
||||
if (!materialized->materializedSchedules[i].runs.empty()) {
|
||||
auto &cores = shared->scheduled[i].cores;
|
||||
assert(cores.size() == 1);
|
||||
cores.push_back((cores.front() + 1) % target.processorCount);
|
||||
auto invalidRun = getPeriodicScheduleReport(graph, *materialized, *shared, *boundaries, timed);
|
||||
assert(invalidRun.getString("status") == "unavailable");
|
||||
assert(invalidRun.getString("reason") == "compact compute runs require one physical core");
|
||||
cores.pop_back();
|
||||
checkedRunOwnership = true;
|
||||
break;
|
||||
}
|
||||
assert(checkedRunOwnership);
|
||||
onnx_mlir::PimInstructionTiming incomplete = timed;
|
||||
incomplete.sharedMemoryRequestLatencyNs.clear();
|
||||
auto unavailable = getPeriodicScheduleReport(graph, *materialized,
|
||||
*shared, *boundaries, incomplete);
|
||||
assert(unavailable.getString("status") == "unavailable");
|
||||
incomplete = timed;
|
||||
incomplete.peerPermissionThenSourceRead = false;
|
||||
unavailable = getPeriodicScheduleReport(graph, *materialized,
|
||||
*shared, *boundaries, incomplete);
|
||||
assert(unavailable.getString("status") == "unavailable");
|
||||
function.print(afterStream);
|
||||
assert(before == after && "periodic diagnostics must not mutate scheduled IR");
|
||||
size_t stores = 0, signals = 0, readyWaits = 0, freeWaits = 0, releases = 0;
|
||||
llvm::DenseSet<int64_t> published;
|
||||
for (const auto &boundary : boundaries->boundaries)
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
// Test-only process guard. The compiler can read static inputs but cannot execute a child program.
|
||||
#define _GNU_SOURCE
|
||||
#include <linux/filter.h>
|
||||
#include <linux/seccomp.h>
|
||||
#include <stddef.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
__attribute__((constructor)) static void forbidExecution(void) {
|
||||
struct sock_filter instructions[] = {
|
||||
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)),
|
||||
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_execve, 0, 1),
|
||||
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS),
|
||||
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_execveat, 0, 1),
|
||||
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS),
|
||||
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
|
||||
};
|
||||
struct sock_fprog program = {sizeof(instructions) / sizeof(instructions[0]), instructions};
|
||||
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) || prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &program))
|
||||
_exit(98);
|
||||
}
|
||||
|
||||
#include <spawn.h>
|
||||
pid_t fork(void) { _exit(99); }
|
||||
pid_t vfork(void) { _exit(99); }
|
||||
int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *actions,
|
||||
const posix_spawnattr_t *attributes, char *const arguments[], char *const environment[]) { _exit(99); }
|
||||
int posix_spawnp(pid_t *pid, const char *path, const posix_spawn_file_actions_t *actions,
|
||||
const posix_spawnattr_t *attributes, char *const arguments[], char *const environment[]) { _exit(99); }
|
||||
|
||||
#include <dlfcn.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
static void rejectHistory(const char *path) {
|
||||
const char *forbidden[] = {"results_comparison.csv", "results_ablation.csv", "fast.json",
|
||||
"selection-frozen.json", "latency.json", ".trace"};
|
||||
for (size_t i = 0; i < sizeof(forbidden) / sizeof(forbidden[0]); ++i)
|
||||
if (strstr(path, forbidden[i])) _exit(97);
|
||||
}
|
||||
#define AUDIT_OPEN(name) \
|
||||
int name(const char *path, int flags, ...) { \
|
||||
rejectHistory(path); \
|
||||
mode_t mode = 0; \
|
||||
if (flags & O_CREAT) { va_list arguments; va_start(arguments, flags); mode = va_arg(arguments, int); va_end(arguments); } \
|
||||
int (*original)(const char *, int, ...) = dlsym(RTLD_NEXT, #name); \
|
||||
return original(path, flags, mode); \
|
||||
}
|
||||
AUDIT_OPEN(open)
|
||||
AUDIT_OPEN(open64)
|
||||
#define AUDIT_FOPEN(name) \
|
||||
FILE *name(const char *path, const char *mode) { \
|
||||
rejectHistory(path); \
|
||||
FILE *(*original)(const char *, const char *) = dlsym(RTLD_NEXT, #name); \
|
||||
return original(path, mode); \
|
||||
}
|
||||
AUDIT_FOPEN(fopen)
|
||||
AUDIT_FOPEN(fopen64)
|
||||
@@ -1,5 +1,5 @@
|
||||
import argparse
|
||||
from collections import defaultdict, deque
|
||||
from collections import Counter, defaultdict, deque
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -13,6 +13,7 @@ from types import SimpleNamespace
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(REPO / "validation/tools/pim/pimcomp/correctness/synchronization"))
|
||||
import global_memory as sync
|
||||
from raptor_validation.pimsim_nn import export_raptor_pimsim_artifact
|
||||
|
||||
|
||||
def read_events(artifact):
|
||||
@@ -121,6 +122,40 @@ def check_lifetimes(streams):
|
||||
return shared, stalled_reader
|
||||
|
||||
|
||||
def check_periodic_estimate(report, streams):
|
||||
assert report["diagnostic_only"] and report["status"] == "estimated", report
|
||||
assert 0 <= report["recurrence_upper_ns"] - report["recurrence_lower_ns"] <= 1
|
||||
assert report["critical_cycle_distance"] > 0
|
||||
ratio = report["critical_cycle_delay_ns"] / report["critical_cycle_distance"]
|
||||
assert report["recurrence_lower_ns"] <= ratio <= report["recurrence_upper_ns"]
|
||||
signals, waits, memory = Counter(), {}, Counter()
|
||||
# The oracle exporter converts this fp32 fixture's addresses to int8 bytes.
|
||||
host_bytes = report["native_host_buffer_bytes"] // 4
|
||||
for core, events in streams.items():
|
||||
for _, op, *args in events:
|
||||
if op == 32:
|
||||
target, register, _ = args
|
||||
signals[core, target, register] += 1
|
||||
elif op == 31:
|
||||
_, register, count = args
|
||||
assert (core, register) not in waits
|
||||
waits[core, register] = count
|
||||
elif op in (25, 26) and args[0] < host_bytes:
|
||||
memory[op, "requests"] += 1
|
||||
memory[op, "bytes"] += args[1]
|
||||
planned = Counter()
|
||||
for event in report["event_registers"]:
|
||||
key = event["core"], event["register"]
|
||||
assert waits.pop(key) == event["expected"]
|
||||
for source in event["sources"]:
|
||||
planned[source["core"], *key] += source["count"]
|
||||
assert not waits and planned == signals
|
||||
for op, direction in ((25, "read"), (26, "write")):
|
||||
for quantity in ("bytes", "requests"):
|
||||
assert report[f"boundary_{direction}_{quantity}"] == memory[op, quantity], (
|
||||
direction, quantity, report[f"boundary_{direction}_{quantity}"], memory[op, quantity])
|
||||
|
||||
|
||||
def run_functional(artifact, inputs, references, outputs, out, policy, seed, reader=None):
|
||||
out.mkdir()
|
||||
command = [str(sync.RUST_BINARY), "--folder", str(artifact),
|
||||
@@ -158,13 +193,17 @@ def main():
|
||||
"--maccel=PIM", "--EmitPimCodegen", "--crossbar-size=128",
|
||||
f"--crossbar-count={weights}", f"--core-count={cores}", "--pipeline=4",
|
||||
f"--pim-target-config={sync.CONFIG_ROOT / arch / 'throughput_config_1000ms.json'}",
|
||||
"--mlir-disable-threading", "--pim-emit-json", "--pim-detect-communication-deadlock"]
|
||||
"--mlir-disable-threading", "--pim-periodic-diagnostics", "--pim-emit-json", "--pim-detect-communication-deadlock"]
|
||||
compiled = subprocess.run(command, capture_output=True, text=True,
|
||||
timeout=120, env=dict(os.environ, OMP_NUM_THREADS="1"))
|
||||
assert compiled.returncode == 0, compiled.stdout + compiled.stderr
|
||||
artifact = out / "pim"
|
||||
streams = read_events(artifact)
|
||||
shared, reader = check_lifetimes(streams)
|
||||
report = json.loads((out / "reports/pipeline_periodic.json").read_text())
|
||||
oracle = out / "pimsim_nn"
|
||||
export_raptor_pimsim_artifact(artifact, oracle)
|
||||
check_periodic_estimate(report, read_events(oracle))
|
||||
for policy, seed in (("greedy", 0), ("randomized", 1), ("randomized", 7)):
|
||||
run_functional(artifact, inputs, references, outputs,
|
||||
out / f"{policy}-{seed}", policy, seed)
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Intermediate emission must stop before unsupported backend transformations."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
import onnx
|
||||
from onnx import TensorProto, helper
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--compiler", required=True)
|
||||
args = parser.parse_args()
|
||||
with tempfile.TemporaryDirectory(prefix="raptor-emission-") as temporary:
|
||||
root = Path(temporary)
|
||||
|
||||
def model(name, elements):
|
||||
tensors = [helper.make_tensor_value_info(n, TensorProto.FLOAT, [1, elements])
|
||||
for n in ("x", "y", "z")]
|
||||
graph = helper.make_graph([helper.make_node("Add", ["x", "y"], ["z"])],
|
||||
name, tensors[:2], tensors[2:])
|
||||
value = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 18)])
|
||||
value.ir_version = 10
|
||||
path = root / f"{name}.onnx"
|
||||
onnx.save(value, path)
|
||||
return path
|
||||
|
||||
small = model("small", 16)
|
||||
# This static type is legal in Spatial. PIM's signed byte-size operand cannot encode it.
|
||||
large = model("large", 536870912)
|
||||
for source, targets in ((small, ("EmitSpatial", "EmitPim", "EmitPimBufferized", "EmitPimCodegen")),
|
||||
(large, ("EmitSpatial", "EmitPim"))):
|
||||
for target in targets:
|
||||
out = root / source.stem / target
|
||||
out.mkdir(parents=True)
|
||||
result = subprocess.run([args.compiler, str(source), "-o", str(out / "model"),
|
||||
"--maccel=PIM", f"--{target}", "--pipeline=2", "--core-count=168",
|
||||
"--crossbar-count=96", "--crossbar-size=128", "--mlir-disable-threading", "--pim-dump-ir",
|
||||
f"--pim-target-config={REPO}/validation/pimsim_configs/pimcomp/arch-a/throughput_config_1000ms.json"],
|
||||
capture_output=True, text=True, timeout=30, env=dict(os.environ, OMP_NUM_THREADS="1"))
|
||||
output = result.stdout + result.stderr
|
||||
if source == large and target == "EmitPim":
|
||||
assert result.returncode != 0 and "host input copy byte size is outside representable range" in output, output
|
||||
continue
|
||||
assert result.returncode == 0, output
|
||||
if target == "EmitPimCodegen":
|
||||
assert (out / "pim/config.json").exists()
|
||||
report = json.loads((out / "reports/pipeline_selection.json").read_text())
|
||||
assert report["generated_candidates"] == 1
|
||||
assert report["single_candidate_analysis_skipped"]
|
||||
assert report["analyzed_candidates"] == report["lowered_candidates"] == 0
|
||||
assert report["unavailable_estimates"] == 0
|
||||
assert not report["reused_lowered_candidate"]
|
||||
assert "no cost comparison required" in report["reason"]
|
||||
else:
|
||||
assert "intermediate emission retains the original schedule" in output
|
||||
assert not (out / "reports/pipeline_selection.json").exists()
|
||||
assert not (out / "reports/pipeline_periodic.json").exists()
|
||||
assert not (out / "pim").exists()
|
||||
name = {"EmitSpatial": "spatial4_scheduled", "EmitPim": "pim0",
|
||||
"EmitPimBufferized": "pim1_buff"}[target]
|
||||
ir = (out / f"dialects/{name}.mlir").read_text()
|
||||
if target == "EmitSpatial":
|
||||
assert "spat.scheduled_compute" in ir and "pim.core" not in ir
|
||||
assert not (out / "dialects/pim0.mlir").exists()
|
||||
elif target == "EmitPim":
|
||||
assert "pim.core" in ir and "tensor<" in ir
|
||||
assert not (out / "dialects/pim1_buff.mlir").exists()
|
||||
else:
|
||||
assert "pim.core" in ir and "memref<" in ir
|
||||
out = root / "explicit-diagnostic"
|
||||
out.mkdir()
|
||||
result = subprocess.run([args.compiler, str(small), "-o", str(out / "model"),
|
||||
"--maccel=PIM", "--EmitSpatial", "--pipeline=2", "--core-count=168",
|
||||
"--crossbar-count=96", "--crossbar-size=128", "--mlir-disable-threading",
|
||||
"--pim-periodic-diagnostics",
|
||||
f"--pim-target-config={REPO}/validation/pimsim_configs/pimcomp/arch-a/throughput_config_1000ms.json"],
|
||||
capture_output=True, text=True, timeout=30)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
assert (out / "reports/pipeline_periodic.json").exists()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,334 @@
|
||||
import argparse
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
def earliest_events(report):
|
||||
graph = report['timing_graph']
|
||||
incoming = [0] * len(graph['events'])
|
||||
outgoing = [[] for _ in incoming]
|
||||
for edge in graph['dependencies']:
|
||||
if edge['distance'] == 0:
|
||||
incoming[edge['target']] += 1
|
||||
outgoing[edge['source']].append(edge)
|
||||
ready = [i for i, count in enumerate(incoming) if count == 0]
|
||||
times = [0] * len(incoming)
|
||||
for source in ready:
|
||||
for edge in outgoing[source]:
|
||||
target = edge['target']
|
||||
times[target] = max(times[target], times[source] + edge['delay_ns'])
|
||||
incoming[target] -= 1
|
||||
if incoming[target] == 0:
|
||||
ready.append(target)
|
||||
assert len(ready) == len(times), 'within-generation graph is cyclic'
|
||||
return graph, times
|
||||
|
||||
|
||||
def record(op, arg=0, a=0, b=0, length=0):
|
||||
return struct.pack('<BBBBiiii', op, 0, 0, 0, arg, a, b, length)
|
||||
|
||||
|
||||
def check_controller(run):
|
||||
scalar = record(1)
|
||||
load = lambda n: record(25, length=n)
|
||||
store = lambda n: record(26, length=n)
|
||||
work = record(27, length=256)
|
||||
barrier = lambda peer: [record(32, arg=peer, a=0), record(31, a=0, b=1)]
|
||||
staggered = [barrier(1) + [load(64), work], barrier(0) + [work, load(64)]]
|
||||
burst = [barrier(1) + [work, load(64)], barrier(0) + [work, load(64)]]
|
||||
a = run(staggered, controller=True, issue=True)
|
||||
b = run(burst, controller=True, issue=True)
|
||||
for report in (a, b):
|
||||
assert report['memory_controller']['status'] == 'estimated'
|
||||
assert report['global_read_bytes'] == 128
|
||||
assert report['global_memory_service_ns'] == 160
|
||||
assert a['memory_controller']['interval_ns'] < b['memory_controller']['interval_ns']
|
||||
assert b['memory_controller'] == run(burst, controller=True, issue=True)['memory_controller']
|
||||
mixed = run([[scalar, load(33), scalar], [scalar, store(128), scalar]],
|
||||
controller=True, issue=True)
|
||||
queued = mixed['memory_controller']
|
||||
assert mixed['global_memory_service_ns'] == 280
|
||||
assert queued['interval_ns'] >= 280
|
||||
assert queued['completed_generations'] >= 4
|
||||
assert any(core['queue_wait_ns'] > 0 for core in queued['per_core'])
|
||||
sizes = run([[scalar, load(1), scalar], [scalar, load(65), scalar]], controller=True, issue=True)
|
||||
assert sizes['global_memory_service_ns'] == 160
|
||||
assert sizes['memory_controller']['interval_ns'] >= 160
|
||||
delayed = [barrier(1) + [load(8192)], barrier(0) + [load(64)]]
|
||||
behind = run(delayed, controller=True, issue=True)
|
||||
assert behind['memory_controller']['status'] == 'estimated'
|
||||
reader = next(core for core in behind['memory_controller']['per_core'] if core['core'] == 1)
|
||||
assert reader['queue_wait_ns'] > 0
|
||||
zero = run([barrier(1) + [record(27, length=128), load(0)], barrier(0) + [store(128)]],
|
||||
controller=True, issue=True)
|
||||
reader = next(core for core in zero['memory_controller']['per_core'] if core['core'] == 0)
|
||||
assert reader['queue_wait_ns'] > 0 # Zero service still queues behind an active request.
|
||||
bounded = run([[scalar, scalar], [scalar, load(65536), scalar]], controller=True, issue=True)
|
||||
assert bounded['memory_controller']['status'] == 'unavailable'
|
||||
shared = [[record(31, a=0, b=2), store(128), record(32, arg=1, a=1), record(32, arg=2, a=1)],
|
||||
[record(32, arg=0, a=0), record(31, a=1, b=1), load(128), record(29, arg=2, length=64)],
|
||||
[record(32, arg=0, a=0), record(31, a=1, b=1), load(128), record(30, arg=1, length=64)]]
|
||||
publication = run(shared, controller=True, issue=True)
|
||||
assert publication['memory_controller']['status'] == 'estimated'
|
||||
assert publication['global_write_requests'] == 1 and publication['global_read_requests'] == 2
|
||||
assert publication['direct_requests'] == 1
|
||||
return [staggered, burst, [[scalar, load(33), scalar], [scalar, store(128), scalar]],
|
||||
[[scalar, load(1), scalar], [scalar, load(65), scalar]], delayed, shared]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--diagnostic', required=True)
|
||||
parser.add_argument('--pimsim', help='Optional ChipTest executable for matched fast-mode timing checks')
|
||||
args = parser.parse_args()
|
||||
repo = Path(__file__).resolve().parents[2]
|
||||
with tempfile.TemporaryDirectory(prefix='raptor-periodic-isa-') as temporary:
|
||||
root = Path(temporary)
|
||||
for arch in ('arch-a', 'arch-b'):
|
||||
config = json.loads((repo / 'validation/pimsim_configs/pimcomp' / arch /
|
||||
'throughput_config_1000ms.json').read_text())
|
||||
config['chip_config']['core_cnt'] = 3
|
||||
latency = {str(i): {str(j): int(i != j) for j in range(3)} for i in range(3)}
|
||||
for i in range(3):
|
||||
latency[str(i)]['-10'] = 2
|
||||
latency['-10'] = {str(i): 2 for i in range(3)}
|
||||
network = root / 'network.json'
|
||||
network.write_text(json.dumps(dict(latency=latency)))
|
||||
config['chip_config']['network_config']['net_config_file_path'] = str(network)
|
||||
path = root / 'hardware.json'
|
||||
path.write_text(json.dumps(config))
|
||||
hardware = config['chip_config']['core_config']
|
||||
command = [args.diagnostic, str(root), f'--pim-target-config={path}',
|
||||
'--core-count=3', '--crossbar-size=128',
|
||||
f'--crossbar-count={hardware["matrix_config"]["xbar_array_count"]}']
|
||||
|
||||
def run(streams, *, issue=False, queues=True, valid=True, controller=False, oracle=False):
|
||||
for artifact in root.glob('core_*.pim'):
|
||||
artifact.unlink()
|
||||
(root / 'config.json').write_text(json.dumps(dict(core_cnt=len(streams),
|
||||
array_group_map={f'core{i}': [i + 1] for i in range(len(streams))})))
|
||||
for i, instructions in enumerate(streams):
|
||||
(root / f'core_{i}.pim').write_bytes(struct.pack('<4sII', b'PIMB', 1,
|
||||
len(instructions)) + b''.join(instructions))
|
||||
before = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in root.glob('core_*.pim')}
|
||||
result = subprocess.run(command + [f'--model-issue={int(issue)}',
|
||||
f'--model-network-queues={int(queues)}',
|
||||
f'--model-memory-controller={int(controller)}', f'--oracle-precision={int(oracle)}'], capture_output=True, text=True)
|
||||
assert (result.returncode == 0) == valid, result.stdout + result.stderr
|
||||
assert before == {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in root.glob('core_*.pim')}
|
||||
if not valid:
|
||||
return result
|
||||
report = json.loads(result.stdout)
|
||||
assert report['diagnostic_only'] and not report['selection_eligible']
|
||||
assert report['status'] == 'estimated'
|
||||
if report['recurrence_lower_ns'] > 1:
|
||||
ratio = report['critical_cycle_delay_ns'] / report['critical_cycle_distance']
|
||||
assert report['recurrence_lower_ns'] <= ratio <= report['recurrence_upper_ns']
|
||||
return report
|
||||
|
||||
bw = record(8, a=8, b=8)
|
||||
load = lambda n: record(25, length=n)
|
||||
store = lambda n: record(26, length=n)
|
||||
send = lambda peer: record(29, arg=peer, length=64)
|
||||
recv = lambda peer: record(30, arg=peer, length=64)
|
||||
sync = lambda peer, reg: record(32, arg=peer, a=reg)
|
||||
wait = lambda reg, n=1: record(31, a=reg, b=n)
|
||||
controller_fixtures = check_controller(run)
|
||||
|
||||
native = run([[record(8, a=32, b=32), load(132), record(10, length=65), store(132)]],
|
||||
issue=True, controller=True, oracle=True)
|
||||
exported = run([[bw, load(33), record(10, length=65), store(33)]], issue=True, controller=True)
|
||||
for key in ('global_read_bytes', 'global_write_bytes', 'global_read_requests',
|
||||
'global_write_requests', 'global_memory_service_ns'):
|
||||
assert native[key] == exported[key], key
|
||||
assert native['memory_controller'] == exported['memory_controller']
|
||||
run([[record(8, a=16, b=16)]], oracle=True, valid=False)
|
||||
run([[load(3)]], oracle=True, valid=False)
|
||||
|
||||
# One scan counts input, constant, and final-output accesses exactly.
|
||||
memory = run([[load(33), load(33), store(33)]])
|
||||
assert memory['global_read_requests'] == 2
|
||||
assert memory['global_read_bytes'] == 66 and memory['global_write_bytes'] == 33
|
||||
assert memory['global_memory_service_ns'] == 260
|
||||
assert memory['per_core'][0]['serial_work_ns'] == 348
|
||||
folded = run([[load(66), store(33)]])
|
||||
assert folded['global_memory_service_ns'] == 220
|
||||
|
||||
scalar = run([[record(1)] * 10], issue=True)
|
||||
assert scalar['per_core'][0]['serial_work_ns'] == 10 * hardware['period']
|
||||
vector = run([[bw, record(10, length=65)]])
|
||||
vector_cost = 2 * 2 * 20 + 3 * 4 + 2 * 30
|
||||
assert vector['per_core'][0]['resource_service_ns'][1] == vector_cost
|
||||
issued = run([[bw, record(10, length=65)]], issue=True)
|
||||
assert issued['per_core'][0]['serial_work_ns'] == vector_cost + 2 * hardware['period']
|
||||
repeated = run([[bw] + [record(10, length=65)] * 10000])
|
||||
assert repeated['per_core'][0]['serial_work_ns'] == 10000 * vector_cost
|
||||
assert repeated['events'] < 10
|
||||
|
||||
matrix = run([[bw, record(9, arg=2)], [bw, record(9, arg=2)]])
|
||||
assert len(matrix['per_core']) == 2
|
||||
assert matrix['per_core'][0]['instructions'] == matrix['per_core'][1]['instructions'] == 2
|
||||
assert matrix['per_core'][0]['resource_service_ns'][0] > 0
|
||||
assert matrix['per_core'][1]['serial_work_ns'] - matrix['per_core'][0]['serial_work_ns'] == 60
|
||||
|
||||
# Equal compute and traffic, different placement of a baseline load.
|
||||
reader = [bw, recv(0), record(9, arg=32), load(1024), send(0)]
|
||||
overlap = run([[send(1), load(1024), recv(1)], reader])
|
||||
serial = run([[load(1024), send(1), recv(1)], reader])
|
||||
assert overlap['global_memory_service_ns'] == serial['global_memory_service_ns']
|
||||
assert overlap['interval_estimate_ns'] < serial['interval_estimate_ns']
|
||||
|
||||
output = run([[send(1)], [recv(0), store(64)]])
|
||||
no_output = run([[send(1)], [recv(0)]])
|
||||
assert output['global_write_requests'] == 1 and output['global_write_bytes'] == 64
|
||||
assert output['direct_requests'] == 1 and output['direct_bytes'] == 64
|
||||
assert output['interval_estimate_ns'] > no_output['interval_estimate_ns']
|
||||
|
||||
# Permission precedes the complete source read; enqueue is immediate.
|
||||
delayed = run([[send(1)], [record(27, length=128), recv(0)]])
|
||||
graph, times = earliest_events(delayed)
|
||||
|
||||
def event_id(core, pc, kind, occurrence=0):
|
||||
return [i for i, event in enumerate(graph['events'])
|
||||
if event == dict(core=core, pc=pc, kind=kind)][occurrence]
|
||||
|
||||
request = event_id(0, 0, 'delivery', 0)
|
||||
permission = event_id(1, 1, 'delivery')
|
||||
enqueue = event_id(0, 0, 'payload-enqueue')
|
||||
delivery = event_id(0, 0, 'delivery', 1)
|
||||
complete = event_id(0, 0, 'send-complete')
|
||||
received = event_id(1, 1, 'receive-complete')
|
||||
assert times[permission] >= max(times[request], 60) + 1
|
||||
assert times[enqueue] == times[permission] + 20
|
||||
assert times[complete] == times[enqueue]
|
||||
assert times[delivery] == times[enqueue] + 2
|
||||
assert times[received] == times[delivery] + 30
|
||||
assert any(edge['source'] == delivery and edge['distance'] == 1
|
||||
for edge in graph['dependencies'])
|
||||
|
||||
# An occupied source FIFO delays request dispatch and permission.
|
||||
busy_routes = copy.deepcopy(latency)
|
||||
busy_routes['0']['2'] = 100
|
||||
network.write_text(json.dumps(dict(latency=busy_routes)))
|
||||
graph, times = earliest_events(run([[sync(2, 0), send(1)], [recv(0)], [wait(0)]]))
|
||||
dispatch = event_id(0, 1, 'fifo-dispatch', 0)
|
||||
enqueue = event_id(0, 1, 'payload-enqueue')
|
||||
complete = event_id(0, 1, 'send-complete')
|
||||
assert times[dispatch] == 100
|
||||
assert times[enqueue] == times[complete] == 122
|
||||
network.write_text(json.dumps(dict(latency=latency)))
|
||||
pairs = run([[send(1), send(1)], [recv(0), recv(0)]])
|
||||
assert pairs['direct_requests'] == 2 and pairs['direct_bytes'] == 128
|
||||
interleaved = run([[wait(0), send(1), sync(1, 1)],
|
||||
[sync(0, 0), recv(0), wait(1)]])
|
||||
assert interleaved['direct_requests'] == 1
|
||||
|
||||
# Exact-count handshakes repeat safely, including shared storage reuse.
|
||||
shared = run([[wait(0, 2), store(128), sync(1, 1), sync(2, 1)],
|
||||
[sync(0, 0), wait(1), load(128)],
|
||||
[sync(0, 0), wait(1), load(128)]])
|
||||
assert shared['global_write_requests'] == 1 and shared['global_read_requests'] == 2
|
||||
assert shared['global_write_bytes'] == 128 and shared['global_read_bytes'] == 256
|
||||
stalled = run([[wait(0, 2), store(128), sync(1, 1), sync(2, 1)],
|
||||
[sync(0, 0), wait(1), load(128)],
|
||||
[bw, sync(0, 0), wait(1), load(128), record(10, length=4096)]])
|
||||
assert stalled['interval_estimate_ns'] > shared['interval_estimate_ns']
|
||||
|
||||
notices = [[sync(1, 0), sync(1, 0), wait(1)], [wait(0, 2), sync(0, 1)]]
|
||||
queued = run(notices)
|
||||
unqueued = run(notices, queues=False)
|
||||
assert queued['interval_estimate_ns'] >= unqueued['interval_estimate_ns']
|
||||
# Delivery starts when SYNC enqueues, before its local completion.
|
||||
slower_clock = copy.deepcopy(config)
|
||||
slower_clock['chip_config']['core_config']['period'] = 8
|
||||
slower_clock['chip_config']['core_config']['local_memory_config'].pop('period')
|
||||
path.write_text(json.dumps(slower_clock))
|
||||
signal = run([[sync(1, 0), wait(1)], [wait(0), sync(0, 1)]])
|
||||
assert signal['interval_estimate_ns'] < 18
|
||||
local = run([[record(27, length=65)]])
|
||||
assert local['per_core'][0]['serial_work_ns'] == 60
|
||||
independent_vector = run([[bw, record(10, length=65)]])
|
||||
assert independent_vector['per_core'][0]['serial_work_ns'] == vector_cost
|
||||
different_memory_clock = copy.deepcopy(slower_clock)
|
||||
different_memory_clock['chip_config']['core_config']['local_memory_config']['period'] = 3
|
||||
different_memory_clock['chip_config']['core_config']['vector_latency_cycle'] = 7
|
||||
path.write_text(json.dumps(different_memory_clock))
|
||||
changed_vector = run([[bw, record(10, length=65)]])
|
||||
assert changed_vector['per_core'][0]['serial_work_ns'] == (vector_cost - 12) * 3 + 21
|
||||
path.write_text(json.dumps(config))
|
||||
|
||||
zero_service = copy.deepcopy(config)
|
||||
zero_service['chip_config']['global_memory_config']['read_latency_cycle'] = 0
|
||||
zero_routes = copy.deepcopy(latency)
|
||||
zero_routes['0']['-10'] = 0
|
||||
zero_routes['0']['1'] = 100
|
||||
network.write_text(json.dumps(dict(latency=zero_routes)))
|
||||
path.write_text(json.dumps(zero_service))
|
||||
prefix = [[load(0), sync(1, 0), load(64), wait(1)], [wait(0), sync(0, 1)]]
|
||||
drained = run(prefix)
|
||||
undrained = run(prefix, queues=False)
|
||||
assert drained['interval_estimate_ns'] > undrained['interval_estimate_ns'] + 20
|
||||
network.write_text(json.dumps(dict(latency=latency)))
|
||||
path.write_text(json.dumps(config))
|
||||
|
||||
if args.pimsim:
|
||||
# Scalar padding avoids the oracle's single-instruction fetch loop.
|
||||
# Golden pairs are (rounded graph estimate, oracle interval), in ns.
|
||||
# Their difference exposes clock-phase/frontend costs, without fitting the model.
|
||||
fixtures = [([[send(1)], [recv(0)]], {}, {}, (56, 57)),
|
||||
([[send(1)], [record(27, length=1024), recv(0)]], {}, {}, (537, 539)),
|
||||
([[send(1)], [recv(0)]], {'memory_period': 3}, {}, (157, 157)),
|
||||
([[send(1)], [recv(0)]], {}, {'peer': 100}, (322, 321)),
|
||||
([[sync(2, 0), send(1)], [recv(0)], [wait(0)]], {}, {'third': 100}, (125, 126)),
|
||||
([[send(1), send(1)], [recv(0), recv(0)]], {}, {}, (111, 112)),
|
||||
([[wait(0), send(1), sync(1, 1)], [sync(0, 0), recv(0), wait(1)]], {}, {}, (60, 65)),
|
||||
([[bw, record(10, length=65)]], {'period': 8, 'memory_period': 3, 'vector': 7}, {}, (473, 488)),
|
||||
([[bw, record(10, length=65)]], {'period': 5, 'memory_period': 2, 'vector': 11}, {}, (333, 340))]
|
||||
fixtures = [(*fixture, False) for fixture in fixtures]
|
||||
controller_expected = [(237, 243), (316, 320), (281, 280), (185, 186), (14145, 14169), (690, 698)]
|
||||
assert len(controller_fixtures) == len(controller_expected)
|
||||
fixtures += [(streams, {}, {}, expected, True) for streams, expected in
|
||||
zip(controller_fixtures, controller_expected)]
|
||||
for streams, clocks, links, expected, controller in fixtures:
|
||||
matched = copy.deepcopy(config)
|
||||
core = matched['chip_config']['core_config']
|
||||
core['period'] = clocks.get('period', 1)
|
||||
core['local_memory_config']['period'] = clocks.get('memory_period', 1)
|
||||
core['vector_latency_cycle'] = clocks.get('vector', 4)
|
||||
matched['sim_config']['sim_time'] = 1
|
||||
path.write_text(json.dumps(matched))
|
||||
routes = copy.deepcopy(latency)
|
||||
routes['0']['1'] = links.get('peer', 1)
|
||||
routes['0']['2'] = links.get('third', 1)
|
||||
network.write_text(json.dumps(dict(latency=routes,
|
||||
energy={s: {d: 0 for d in row} for s, row in routes.items()})))
|
||||
program = streams if controller else [[record(1)] + stream + [record(1)] for stream in streams]
|
||||
prediction = run(program, issue=True, controller=controller)
|
||||
result = subprocess.run([args.pimsim, str(root), str(path), '--gui=false', '--fast'],
|
||||
capture_output=True, text=True, timeout=30)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
assert 'Fast throughput converged' in result.stdout
|
||||
measured = float(re.search(r'average latency:\s+(\S+)', result.stdout)[1]) * 1e6
|
||||
estimate = prediction['memory_controller']['interval_ns'] if controller else prediction['interval_estimate_ns']
|
||||
assert (round(estimate), round(measured)) == expected
|
||||
path.write_text(json.dumps(config))
|
||||
network.write_text(json.dumps(dict(latency=latency)))
|
||||
|
||||
run([[send(1), recv(1)], [send(0), recv(0)]], valid=False)
|
||||
run([[sync(1, 0)], [wait(0, 2)]], valid=False)
|
||||
run([[record(21, length=1)]], valid=False)
|
||||
run([[]], valid=False)
|
||||
unsupported = copy.deepcopy(config)
|
||||
unsupported['chip_config']['core_config']['rob_size'] = 2
|
||||
path.write_text(json.dumps(unsupported))
|
||||
run([[load(33)]], valid=False)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -45,6 +45,25 @@ def main():
|
||||
if not valid:
|
||||
assert "Pim target config" in result.stdout, result.stdout
|
||||
|
||||
# Optional diagnostic routes must not change legacy compilation support.
|
||||
network_path = Path(network["net_config_file_path"])
|
||||
for route in (None, 1e100):
|
||||
candidate = copy.deepcopy(config)
|
||||
candidate["chip_config"]["core_config"]["global_memory_switch_id"] = 999
|
||||
routes = json.loads(network_path.read_text())
|
||||
if route is not None:
|
||||
routes["latency"]["999"] = {}
|
||||
for core in range(168):
|
||||
routes["latency"][str(core)]["999"] = route
|
||||
routes["latency"]["999"][str(core)] = route
|
||||
route_path = root / "routes.json"
|
||||
route_path.write_text(json.dumps(routes))
|
||||
candidate["chip_config"]["network_config"]["net_config_file_path"] = str(route_path)
|
||||
path.write_text(json.dumps(candidate))
|
||||
result = subprocess.run(command, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT, text=True)
|
||||
assert result.returncode == 0, result.stdout
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Production selection must use static compiler inputs only."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def check_selected_program(out):
|
||||
report = json.loads((out / "reports/pipeline_selection.json").read_text())
|
||||
program = json.loads((out / "pim/config.json").read_text())
|
||||
digest = hashlib.sha256()
|
||||
for core in range(program["core_cnt"]):
|
||||
digest.update((out / f"pim/core_{core}.pim").read_bytes())
|
||||
for count in program["array_group_map"][f"core{core}"]:
|
||||
digest.update(f"{count},".encode())
|
||||
digest.update(b";")
|
||||
assert digest.hexdigest().upper() == report["candidates"][report["selection"]]["identity"], \
|
||||
"emitted program differs from the analyzed winner"
|
||||
assert report["reused_lowered_candidate"]
|
||||
for name in ("spatial3_scheduled_no_comm.txt", "memory_report.txt"):
|
||||
assert (out / "reports" / name).stat().st_size > 0, name
|
||||
return report
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--compiler", required=True)
|
||||
args = parser.parse_args()
|
||||
compiler = str(Path(args.compiler).resolve())
|
||||
model = REPO / "validation/networks/pimcomp_models/googlenet/googlenet-12-pimsim-nn.onnx"
|
||||
with tempfile.TemporaryDirectory(prefix="raptor-static-selection-") as temporary:
|
||||
root = Path(temporary)
|
||||
history = root / "validation/tools/pim/pimcomp/compare/results_comparison.csv"
|
||||
history.parent.mkdir(parents=True)
|
||||
profile = root / "profiles/latency.json"
|
||||
profile.parent.mkdir()
|
||||
trap = root / "bin"
|
||||
trap.mkdir()
|
||||
for name in ("ChipTest", "pimsim", "raptor-periodic", "perf"):
|
||||
path = trap / name
|
||||
path.write_text("#!/bin/sh\necho forbidden execution >> '" + str(root / "executed") + "'\nexit 99\n")
|
||||
path.chmod(0o755)
|
||||
guard = root / "static-audit.so"
|
||||
subprocess.run([os.environ.get("CC", "cc"), "-shared", "-fPIC",
|
||||
str(REPO / "test/PIM/StaticSchedulingAudit.c"), "-o", str(guard)], check=True)
|
||||
env = dict(os.environ, LD_PRELOAD=str(guard), PATH=str(trap) + os.pathsep + os.environ["PATH"], OMP_NUM_THREADS="1")
|
||||
decisions = []
|
||||
for iteration in range(3):
|
||||
if iteration == 0:
|
||||
history.write_text("network,throughput\ngooglenet,1e99\n")
|
||||
profile.write_text('{"candidate":999,"measured_latency":1}')
|
||||
elif iteration == 1:
|
||||
history.write_bytes(b"invalid historical data\x00")
|
||||
profile.write_text('{"candidate":0,"measured_latency":1e99}')
|
||||
else:
|
||||
history.unlink()
|
||||
shutil.rmtree(profile.parent)
|
||||
out = root / f"run-{iteration}"
|
||||
out.mkdir()
|
||||
command = [compiler, str(model), "-o", str(out / "model"), "--maccel=PIM",
|
||||
"--EmitPimCodegen", "--core-count=138", "--crossbar-count=128", "--crossbar-size=128",
|
||||
"--pipeline=4", "--mlir-disable-threading", "--pim-detect-communication-deadlock",
|
||||
f"--pim-target-config={REPO}/validation/pimsim_configs/pimcomp/arch-b/throughput_config_1000ms.json"]
|
||||
result = subprocess.run(command, cwd=root, env=env, capture_output=True, text=True, timeout=180)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
report = json.loads((out / "reports/pipeline_selection.json").read_text())
|
||||
assert report["static_analysis"] and report["temporary_disk_bytes"] == 0
|
||||
assert report["analyzed_candidates"] > 1, report
|
||||
check_selected_program(out)
|
||||
assert not report["reconstructed_spatial_artifacts"]
|
||||
assert not (out / "dialects").exists()
|
||||
assert not list(out.glob("candidate*"))
|
||||
decisions.append((report["selection"], [(c["identity"], c.get("interval_ns"), c.get("alternative_tie_interval_ns"))
|
||||
for c in report["candidates"]]))
|
||||
# Keep the test's disk peak to one selected program.
|
||||
shutil.rmtree(out)
|
||||
assert decisions[0] == decisions[1] == decisions[2], "historical files or address allocation changed static selection"
|
||||
# Exercise the same winner with and without explicit Spatial artifacts.
|
||||
vgg = REPO / "validation/networks/pimcomp_models/vgg8/vgg8-mnist-reconstructed.onnx"
|
||||
for diagnostics in (False, True):
|
||||
out = root / f"vgg-{diagnostics}"
|
||||
out.mkdir()
|
||||
command = [compiler, str(vgg), "-o", str(out / "model"), "--maccel=PIM", "--EmitPimCodegen",
|
||||
"--pipeline=2", "--core-count=138", "--crossbar-count=128", "--crossbar-size=128",
|
||||
"--mlir-disable-threading", "--pim-detect-communication-deadlock",
|
||||
f"--pim-target-config={REPO}/validation/pimsim_configs/pimcomp/arch-b/throughput_config_1000ms.json"]
|
||||
if diagnostics:
|
||||
command += ["--pim-export-spatial-dataflow=all", "--pim-dump-ir", "--pim-periodic-diagnostics"]
|
||||
result = subprocess.run(command, cwd=root, env=env, capture_output=True, text=True, timeout=90)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
report = check_selected_program(out)
|
||||
assert report["selection"] != 0 and report["reconstructed_spatial_artifacts"] == diagnostics
|
||||
identity = report["candidates"][report["selection"]]["identity"]
|
||||
schedule = (out / "reports/spatial3_scheduled_no_comm.txt").read_bytes()
|
||||
if diagnostics:
|
||||
assert identity == previous_identity and schedule == previous_schedule
|
||||
for stage in ("spatial3_scheduled_no_comm", "spatial4_scheduled"):
|
||||
for suffix in ("nodes.csv", "edges.csv"):
|
||||
assert (out / f"reports/{stage}.{suffix}").stat().st_size > 0
|
||||
assert (out / "reports/pipeline_periodic.json").exists()
|
||||
assert (out / "dialects/spatial4_scheduled.mlir").exists()
|
||||
previous_identity, previous_schedule = identity, schedule
|
||||
shutil.rmtree(out)
|
||||
config_path = REPO / "validation/pimsim_configs/pimcomp/arch-a/throughput_config_1000ms.json"
|
||||
unsupported = json.loads(config_path.read_text())
|
||||
unsupported["chip_config"]["core_config"]["rob_size"] = 2
|
||||
network = unsupported["chip_config"]["network_config"]
|
||||
network["net_config_file_path"] = str((config_path.parent / network["net_config_file_path"]).resolve())
|
||||
hardware = root / "unsupported-target.json"
|
||||
hardware.write_text(json.dumps(unsupported))
|
||||
out = root / "fallback"
|
||||
out.mkdir()
|
||||
command = [compiler, str(REPO / "validation/networks/pimcomp_models/vgg8/vgg8-mnist-reconstructed.onnx"),
|
||||
"-o", str(out / "model"), "--maccel=PIM", "--EmitPimCodegen", "--pipeline=4",
|
||||
"--core-count=168", "--crossbar-count=96", "--crossbar-size=128", "--mlir-disable-threading",
|
||||
f"--pim-target-config={hardware}"]
|
||||
result = subprocess.run(command, cwd=root, env=env, capture_output=True, text=True, timeout=60)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
report = json.loads((out / "reports/pipeline_selection.json").read_text())
|
||||
assert report["selection"] == 0 and report["analyzed_candidates"] == 0
|
||||
assert report["generated_candidates"] == 1 and report["lowered_candidates"] == 0
|
||||
assert "ROB capacity one" in report["reason"] and report["unavailable_estimates"] > 0
|
||||
assert report["temporary_disk_bytes"] == 0 and not list(root.glob("candidate*"))
|
||||
shutil.rmtree(out)
|
||||
out.mkdir()
|
||||
command[-1] = f"--pim-target-config={config_path}"
|
||||
command += ["--pim-disable-synchronization"]
|
||||
result = subprocess.run(command, cwd=root, env=env, capture_output=True, text=True, timeout=60)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
report = json.loads((out / "reports/pipeline_selection.json").read_text())
|
||||
assert report["selection"] == 0 and report["analyzed_candidates"] == 0
|
||||
assert report["generated_candidates"] == 1 and report["lowered_candidates"] == 0
|
||||
assert "synchronization ablation" in report["reason"]
|
||||
assert not (root / "executed").exists(), "production compiler executed a diagnostic or simulator"
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user