Files
Raptor/src/PIM/Compiler/PimSpatialCost.cpp
T
NiccoloN 5f2db946f0
Validate Operations / validate-operations (push) Has been cancelled
better compile times for throughput scheduling
fix failing no-plan throughput ablation runs
update results
2026-10-28 16:34:48 +01:00

664 lines
33 KiB
C++

#include "PimSpatialCost.hpp"
#include "PimInstructionTiming.hpp"
#include "PimTimingArithmetic.hpp"
#include "PimBinaryFormat.hpp"
#include "PimCompilerUtils.hpp"
#include "PimCompilerOptions.hpp"
#include "PimScheduleDiagnostic.hpp"
#include "src/Accelerators/PIM/Common/IR/ConstantUtils.hpp"
#include "src/Accelerators/PIM/Common/IR/CopyAccessPlan.hpp"
#include "src/Accelerators/PIM/Common/IR/ShapeUtils.hpp"
#include "src/Accelerators/PIM/Common/IR/ShapingUtils.hpp"
#include "src/Accelerators/PIM/Conversion/SpatialToPim/ComputeLikeRegionUtils.hpp"
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/DeferredProjectionAnalysis.hpp"
#include "mlir/Dialect/Linalg/IR/Linalg.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/SCF/IR/SCF.h"
#include "mlir/IR/Matchers.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/Support/MathExtras.h"
#include <chrono>
#include <array>
#include <map>
#include <limits>
using namespace mlir;
using namespace onnx_mlir;
using namespace onnx_mlir::spatial;
using pim_timing::add;
using pim_timing::mul;
using pim_timing::ceil;
namespace {
using Event = PimExecutionEvent;
using Sequence = std::vector<Event>;
enum class Residence { Local, Host, Constant, Zero, CapturedWeight };
PimPeriodicEstimate unavailableCost(llvm::StringRef reason) {
PimPeriodicEstimate result;
result.cost.reason = reason.str();
result.report = llvm::json::Object{{"status", "unavailable"}, {"cost_available", false},
{"convergence_proved", nullptr}, {"lowering_supported", nullptr},
{"safe_for_selection", false}, {"reason", reason.str()}};
return result;
}
class Extraction {
public:
const PimInstructionTiming &target;
bool diagnostics;
bool omitSynchronization;
PimExecutionProgram program;
std::string error, loweringReason;
StaticLoweringSupport loweringSupport = StaticLoweringSupport::Supported;
std::map<std::string, int64_t> gaps;
int64_t visited = 0, constantLoads = 0;
explicit Extraction(const PimInstructionTiming &target, bool diagnostics, bool omitSynchronization)
: target(target), diagnostics(diagnostics), omitSynchronization(omitSynchronization),
program(target.processorCount) {}
bool build(ModuleOp module);
private:
// Bound interpretation per physical core, independently of batch lane count.
static constexpr size_t maximumCoreVisits = 1000000;
size_t coreVisits = 0;
int64_t currentCore = -1;
llvm::SmallDenseSet<int64_t, 16> assignedCores;
DenseMap<Value, Residence> residence;
DenseMap<Value, CopyAccessPlan> publicationAccess;
DenseMap<Value, SmallVector<unsigned, 2>> directOutputs;
llvm::SmallDenseSet<Value, 4> compactStorage;
llvm::SmallPtrSet<Operation *, 32> indexed;
StaticIndexEnvironment environment;
Residence storage(Value value);
uint64_t elements(Type type) {
auto shape = dyn_cast<ShapedType>(type);
if (!shape || !shape.hasStaticShape()) {
error = "abstract work requires a static shaped payload";
return 0;
}
if (!shape.getElementType().isIntOrFloat() || shape.getElementTypeBitWidth() != 32) {
error = "abstract precision projection requires 32-bit elements";
return 0;
}
uint64_t result = 1;
for (int64_t dimension : shape.getShape()) result = mul(result, dimension);
return result;
}
uint64_t bytes(Type type) {
uint64_t count = elements(type);
auto shaped = dyn_cast<ShapedType>(type);
if (!shaped || !shaped.getElementType().isIntOrFloat()) {
error = "abstract transfer requires a scalar integer or floating element";
return 0;
}
uint64_t nativeBytes = ceil(mul(count, shaped.getElementTypeBitWidth()), 8);
if (nativeBytes > std::numeric_limits<int32_t>::max()) {
loweringSupport = StaticLoweringSupport::Unknown;
loweringReason = "native transfer size requires backend normalization and size verification";
}
return ceil(mul(count, target.computeBitwidth), 8);
}
void work(Sequence &sequence, uint64_t ns, Event::WorkClass resource = Event::LocalCopy) {
if (!ns) return;
if (!sequence.empty() && sequence.back().kind == Event::Work
&& sequence.back().workClass == resource)
sequence.back().amount = add(sequence.back().amount, ns);
else {
sequence.push_back({Event::Work, ns});
sequence.back().workClass = resource;
}
}
uint64_t localWork(uint64_t bytes, bool read, bool write) const {
return getPimLocalTransferWorkNs(target, bytes, read, write);
}
void materialize(Value value, Sequence &sequence);
bool accessSlice(tensor::ExtractSliceOp slice, Sequence &sequence, bool host);
bool block(Block &body, Sequence &sequence);
bool operation(Operation &op, Sequence &sequence);
bool loop(scf::ForOp op, Sequence &sequence);
bool core(Operation *op, int64_t physicalCore, unsigned lane);
};
Residence Extraction::storage(Value value) {
if (auto it = residence.find(value); it != residence.end()) return it->second;
Attribute constant;
if (matchPattern(value, m_Constant(&constant)))
return isZeroBitPatternSplat(constant) ? Residence::Zero : Residence::Constant;
if (auto slice = value.getDefiningOp<tensor::ExtractSliceOp>()) return storage(slice.getSource());
if (auto collapse = value.getDefiningOp<tensor::CollapseShapeOp>()) return storage(collapse.getSrc());
if (auto expand = value.getDefiningOp<tensor::ExpandShapeOp>()) return storage(expand.getSrc());
if (auto cast = value.getDefiningOp<tensor::CastOp>()) return storage(cast.getSource());
if (auto branch = value.getDefiningOp<scf::IfOp>()) {
auto condition = evaluateDeferredIndex(branch.getCondition(), environment);
if (succeeded(condition)) {
Region &region = *condition ? branch.getThenRegion() : branch.getElseRegion();
return storage(region.front().getTerminator()->getOperand(cast<OpResult>(value).getResultNumber()));
}
}
if (auto arg = dyn_cast<BlockArgument>(value)) {
if (auto loop = dyn_cast_or_null<scf::ForOp>(arg.getOwner()->getParentOp()))
if (arg.getArgNumber()) return Residence::Local;
return Residence::Host;
}
if (isa_and_nonnull<SpatVMMOp, SpatVAddOp, SpatVSubOp, SpatVMulOp,
SpatVMaxOp, SpatVVDMulOp, SpatVAvgOp, SpatReluOp, SpatSigmoidOp, SpatSoftmaxOp,
SpatChannelReceiveOp, SpatHostWaitLoadOp, SpatScheduledCompute,
SpatScheduledComputeBatch, SpatConcatOp, tensor::EmptyOp,
tensor::InsertSliceOp, tensor::PadOp, linalg::TransposeOp, scf::ForOp>(value.getDefiningOp()))
return Residence::Local;
error = "abstract storage residence is unavailable for "
+ value.getDefiningOp()->getName().getStringRef().str();
return Residence::Local; // The caller discards the estimate when error is set.
}
void Extraction::materialize(Value value, Sequence &sequence) {
auto place = storage(value);
if (place == Residence::Host || place == Residence::Constant || place == Residence::CapturedWeight) {
sequence.push_back({Event::Load, bytes(value.getType())});
// Captured weights remain block arguments; only direct global zero loads fold to fills.
if (place == Residence::Constant || place == Residence::CapturedWeight) {
++constantLoads;
sequence.back().constant = true;
}
} else if (place == Residence::Zero) {
work(sequence, localWork(bytes(value.getType()), false, true), Event::Fill);
}
}
bool Extraction::accessSlice(tensor::ExtractSliceOp slice, Sequence &sequence, bool host) {
auto source = computeRowMajorStridesChecked(slice.getSourceType().getShape());
auto destination = computeRowMajorStridesChecked(slice.getStaticSizes());
if (failed(source) || failed(destination)) { error = "abstract slice geometry unavailable"; return false; }
SmallVector<int64_t> strides;
for (auto [stride, scale] : llvm::zip(*source, slice.getStaticStrides())) {
int64_t result;
if (scale <= 0 || llvm::MulOverflow(stride, scale, result)) {
error = "abstract slice stride unavailable"; return false;
}
strides.push_back(result);
}
auto copy = CopyAccessPlan::build(slice.getStaticSizes(), strides, *destination);
if (failed(copy)) { error = "abstract slice access plan unavailable"; return false; }
uint64_t size = ceil(mul(copy->getRunElements(), target.computeBitwidth), 8);
if (host) {
sequence.push_back({Event::Repeat, static_cast<uint64_t>(copy->getRunCount()),
0, 0, 0, {{Event::Load, size}}});
residence[slice.getResult()] = Residence::Local;
compactStorage.insert(slice.getResult());
} else if (compactStorage.contains(slice.getSource())
&& slice.getSourceType().getRank() == slice.getType().getRank()
&& llvm::all_of(slice.getResult().getUsers(), [](Operation *user) {
return isa<SpatHostStoreSyncOp>(user);
})) {
// Publication-only slices retain the compact source's subview geometry.
publicationAccess.insert_or_assign(slice.getResult(), *copy);
} else if (copy->getRunCount() > 1) {
if (diagnostics) ++gaps["local slice materialization and forwarding"];
work(sequence, mul(copy->getRunCount(), localWork(size, true, true)));
}
if (compactStorage.contains(slice.getSource()) && copy->getRunCount() == 1)
compactStorage.insert(slice.getResult());
return true;
}
bool Extraction::loop(scf::ForOp op, Sequence &sequence) {
auto lower = evaluateDeferredIndex(op.getLowerBound(), environment);
auto upper = evaluateDeferredIndex(op.getUpperBound(), environment);
auto step = evaluateDeferredIndex(op.getStep(), environment);
if (failed(lower) || failed(upper) || failed(step) || *step <= 0) {
error = "abstract loop has unavailable static bounds"; return false;
}
for (Value initial : op.getInitArgs()) materialize(initial, sequence);
int64_t distance = 0;
if (*upper > *lower && llvm::SubOverflow(*upper, *lower, distance)) {
error = "unrepresentable abstract loop trip count"; return false;
}
uint64_t count = ceil(distance, *step);
bool indexSensitive = indexed.contains(op);
if (indexSensitive && count > 100000) {
error = "abstract indexed loop exceeds analysis budget"; return false;
}
if (!count) return true;
if (indexSensitive) {
for (uint64_t i = 0; i < count; ++i) {
int64_t induction;
if (llvm::AddOverflow(*lower, static_cast<int64_t>(mul(i, *step)), induction)) {
error = "unrepresentable abstract induction value"; return false;
}
environment.bindings[op.getInductionVar()] = induction;
if (!block(*op.getBody(), sequence)) return false;
}
} else {
environment.bindings[op.getInductionVar()] = *lower;
Event repeat{Event::Repeat, count};
if (!block(*op.getBody(), repeat.body)) return false;
sequence.push_back(std::move(repeat));
}
environment.bindings.erase(op.getInductionVar());
return true;
}
bool Extraction::operation(Operation &op, Sequence &sequence) {
if (auto loopOp = dyn_cast<scf::ForOp>(op)) return loop(loopOp, sequence);
if (auto branch = dyn_cast<scf::IfOp>(op)) {
auto condition = evaluateDeferredIndex(branch.getCondition(), environment);
if (failed(condition)) { error = "abstract branch condition is unavailable"; return false; }
Region &region = *condition ? branch.getThenRegion() : branch.getElseRegion();
return region.empty() || block(region.front(), sequence);
}
auto index = [&](Value value) -> int64_t {
auto result = evaluateDeferredIndex(value, environment);
if (failed(result)) { error = "abstract communication index is unavailable"; return -1; }
return *result;
};
if (auto sync = dyn_cast<SpatSyncOp>(op)) {
if (!omitSynchronization)
sequence.push_back({Event::Signal, 0, index(sync.getTargetCoreId()), index(sync.getEventRegister())});
} else if (auto wait = dyn_cast<SpatWaitOp>(op)) {
if (!omitSynchronization) {
int64_t count = index(wait.getWaitValue());
if (count) sequence.push_back({Event::Wait, 0, 0, index(wait.getEventRegister()), count});
}
} else if (auto send = dyn_cast<SpatChannelSendOp>(op)) {
materialize(send.getInput(), sequence);
sequence.push_back({Event::Send, bytes(send.getInput().getType()), index(send.getTargetCoreId())});
} else if (auto recv = dyn_cast<SpatChannelReceiveOp>(op)) {
sequence.push_back({Event::Receive, bytes(recv.getOutput().getType()), index(recv.getSourceCoreId())});
} else if (auto store = dyn_cast<SpatHostStoreSyncOp>(op)) {
materialize(store.getInput(), sequence);
if (auto plan = publicationAccess.find(store.getInput()); plan != publicationAccess.end())
sequence.push_back({Event::Repeat, static_cast<uint64_t>(plan->second.getRunCount()),
0, 0, 0, {{Event::Store, ceil(mul(plan->second.getRunElements(), target.computeBitwidth), 8)}}});
else sequence.push_back({Event::Store, bytes(store.getInput().getType())});
if (!omitSynchronization)
sequence.push_back({Event::Signal, 0, index(store.getTargetCoreId()), index(store.getEventRegister())});
} else if (auto load = dyn_cast<SpatHostWaitLoadOp>(op)) {
if (!omitSynchronization) {
int64_t count = index(load.getWaitValue());
if (count) sequence.push_back({Event::Wait, 0, 0, index(load.getEventRegister()), count});
}
sequence.push_back({Event::Load, bytes(load.getOutput().getType())});
} else if (auto vmm = dyn_cast<SpatVMMOp>(op)) {
materialize(vmm.getInput(), sequence);
auto weight = dyn_cast<RankedTensorType>(vmm.getWeight().getType());
if (!weight || weight.getRank() != 2 || !weight.hasStaticShape() || !target.matrixColumns
|| weight.getDimSize(1) <= 0
|| static_cast<uint64_t>(weight.getDimSize(1)) % target.matrixColumns
|| weight.getDimSize(0) <= 0
|| static_cast<uint64_t>(weight.getDimSize(0)) > target.matrixRows
|| weight.getEncoding() || !weight.getElementType().isIntOrFloat()
|| weight.getElementTypeBitWidth() != 32) {
error = "unavailable physical matrix weight geometry"; return false;
}
if (diagnostics && static_cast<uint64_t>(weight.getDimSize(0)) < target.matrixRows)
++gaps["matrix input padding and copy forwarding"];
uint64_t output = getPimMatrixOutputBytes(target, target.matrixCellBits,
pim_binary::kMatrixWeightPrecisionBits, weight.getDimSize(1) / target.matrixColumns,
ceil(target.computeBitwidth, 8));
work(sequence, getPimMatrixWorkNs(target, target.computeBitwidth, output), Event::Matrix);
} else if (auto softmax = dyn_cast<SpatSoftmaxOp>(op)) {
materialize(softmax.getInput(), sequence);
// Pimsim-nn omits vsoftmax itself. Keep any preceding input materialization.
} else if (isa<SpatVAddOp, SpatVSubOp, SpatVMulOp, SpatVMaxOp,
SpatVVDMulOp, SpatVAvgOp, SpatReluOp, SpatSigmoidOp>(op)) {
for (Value operand : op.getOperands()) materialize(operand, sequence);
uint64_t width = ceil(target.computeBitwidth, 8);
work(sequence, getPimVectorWorkNs(target, elements(op.getOperand(0).getType()),
width, width, op.getNumOperands() == 2), Event::Vector);
} else if (auto extract = dyn_cast<tensor::ExtractSliceOp>(op)) {
auto place = storage(extract.getSource());
if (place == Residence::Host || place == Residence::Local)
if (!accessSlice(extract, sequence, place == Residence::Host)) return false;
} else if (auto insert = dyn_cast<tensor::InsertSliceOp>(op)) {
materialize(insert.getSource(), sequence);
uint64_t size = bytes(insert.getSource().getType());
work(sequence, localWork(size, true, true));
if (compactStorage.contains(insert.getDest())) compactStorage.insert(insert.getResult());
if (diagnostics) ++gaps["output copy forwarding"];
} else if (auto transpose = dyn_cast<linalg::TransposeOp>(op)) {
materialize(transpose.getInput(), sequence);
auto type = cast<ShapedType>(transpose.getInput().getType());
uint64_t volume = elements(type);
if (!volume) {
if (error.empty()) error = "zero-element transpose has no abstract timing contract";
return false;
}
if (failed(computeRowMajorStridesChecked(type.getShape()))) {
error = "abstract transpose geometry unavailable"; return false;
}
auto run = getTransposeRun(type.getShape(), transpose.getPermutation());
uint64_t width = ceil(target.computeBitwidth, 8);
uint64_t runBytes = mul(run.elements, width);
uint64_t cost = run.sourceStride == 1
? localWork(runBytes, true, true)
: getPimVectorWorkNs(target, run.elements, width, width, false);
work(sequence, mul(volume / run.elements, cost),
run.sourceStride == 1 ? Event::LocalCopy : Event::VectorCopy);
if (diagnostics) ++gaps["transpose alias and constant folding"];
} else if (auto pad = dyn_cast<tensor::PadOp>(op)) {
materialize(pad.getSource(), sequence);
work(sequence, localWork(bytes(pad.getResult().getType()), false, true), Event::Fill);
work(sequence, localWork(bytes(pad.getSource().getType()), true, true));
if (diagnostics) ++gaps["padding fill and copy normalization"];
} else if (auto concat = dyn_cast<SpatConcatOp>(op)) {
for (Value input : concat.getInputs()) {
materialize(input, sequence);
uint64_t size = bytes(input.getType());
work(sequence, localWork(size, true, true));
}
compactStorage.insert(concat.getOutput());
if (diagnostics) ++gaps["concat alias and copy elimination"];
} else if (auto empty = dyn_cast<tensor::EmptyOp>(op)) {
compactStorage.insert(empty.getResult());
} else if (isa<arith::ConstantOp, tensor::ExtractOp,
tensor::CollapseShapeOp, tensor::ExpandShapeOp, tensor::CastOp,
scf::YieldOp, SpatYieldOp>(op) || isPureIndexComputationOp(&op)) {
// Compile-time shape/index work has no device execution cost.
} else if (auto parallel = dyn_cast<SpatInParallelOp>(op)) {
auto batch = parallel->getParentOfType<SpatScheduledComputeBatch>();
auto first = batch ? batch.getOutputArgument(0) : std::nullopt;
if (!first) { error = "unavailable abstract batch output mapping"; return false; }
for (Operation &nested : parallel.getRegion().front()) {
auto insert = dyn_cast<tensor::ParallelInsertSliceOp>(nested);
auto destination = insert ? dyn_cast<BlockArgument>(insert.getDest()) : BlockArgument{};
if (!destination || destination.getArgNumber() < first->getArgNumber()) {
error = "unsupported abstract batch output"; return false;
}
unsigned result = destination.getArgNumber() - first->getArgNumber();
if (result >= batch.getNumResults()) { error = "invalid abstract batch output"; return false; }
if (succeeded(getDirectReturnOperandIndex(cast<OpResult>(batch.getResult(result))))) {
materialize(insert.getSource(), sequence);
sequence.push_back({Event::Store, bytes(insert.getSource().getType())});
} else if (!batch.getResult(result).use_empty()) {
error = "unavailable indirect batch output collection"; return false;
}
}
} else {
error = "unsupported abstract operation: " + op.getName().getStringRef().str();
return false;
}
return error.empty();
}
bool Extraction::block(Block &body, Sequence &sequence) {
for (Operation &op : body) {
++visited;
if (++coreVisits > maximumCoreVisits) {
error = "abstract extraction budget exceeded on physical core "
+ std::to_string(currentCore);
return false;
}
if (!operation(op, sequence)) return false;
for (Value result : op.getResults())
if (auto outputs = directOutputs.find(result); outputs != directOutputs.end())
// Lowering inserts each store immediately after the shared producer.
for (unsigned destination : llvm::reverse(outputs->second)) {
(void)destination; // Distinct host destinations require distinct stores.
sequence.push_back({Event::Store, bytes(result.getType())});
}
}
return true;
}
bool Extraction::core(Operation *op, int64_t physicalCore, unsigned lane) {
if (physicalCore < 0 || physicalCore >= static_cast<int64_t>(program.size())) {
loweringSupport = StaticLoweringSupport::Unsupported;
error = "physical core ID is outside the target: " + std::to_string(physicalCore); return false;
}
if (!assignedCores.insert(physicalCore).second) {
loweringSupport = StaticLoweringSupport::Unsupported;
error = "duplicate physical core assignment: " + std::to_string(physicalCore); return false;
}
coreVisits = 0; currentCore = physicalCore;
residence.clear(); publicationAccess.clear(); directOutputs.clear(); compactStorage.clear();
environment.bindings.clear();
ValueRange inputs, weights;
auto single = dyn_cast<SpatScheduledCompute>(op);
auto batch = dyn_cast<SpatScheduledComputeBatch>(op);
if (single) { inputs = single.getInputs(); weights = single.getWeights(); }
else { inputs = batch.getInputs(); weights = batch.getWeights(); environment.bindings[*batch.getLaneArgument()] = lane; }
Sequence &sequence = program[physicalCore];
if (single) {
auto yield = cast<SpatYieldOp>(single.getBody().front().getTerminator());
for (auto [result, value] : llvm::zip(single.getResults(), yield.getOperands()))
if (auto destination = getDirectReturnOperandIndex(cast<OpResult>(result)); succeeded(destination)) {
if (!value.getDefiningOp() || value.getDefiningOp()->getBlock() != &single.getBody().front()) {
error = "unavailable direct output insertion position"; return false;
}
directOutputs[value].push_back(*destination);
} else if (!result.use_empty()) {
error = "unavailable indirect compute output collection"; return false;
}
}
for (unsigned i = 0; i < weights.size(); ++i)
residence[single ? *single.getWeightArgument(i) : *batch.getWeightArgument(i)] = Residence::CapturedWeight;
for (unsigned i = 0; i < inputs.size(); ++i) {
Value argument = single ? *single.getInputArgument(i) : *batch.getInputArgument(i);
auto plan = planComputeInputMaterialization(op, i);
if (failed(plan)) { error = "input materialization plan unavailable"; return false; }
residence[argument] = storage(inputs[i]);
// FuncOpArgToGlobalMemoryPattern removes this input and exposes the host
// tensor in the body before entry-copy materialization runs.
if (*plan == ComputeInputMaterialization::ForwardFunctionInput) {
if (diagnostics) ++gaps["function-input whole-load versus slice materialization"];
continue;
}
if (*plan == ComputeInputMaterialization::CopyAtEntry) {
materialize(inputs[i], sequence);
residence[argument] = Residence::Local;
compactStorage.insert(argument);
if (diagnostics) ++gaps["input host slicing and receive sinking"];
}
}
return block(op->getRegion(0).front(), sequence);
}
bool Extraction::build(ModuleOp module) {
bool okay = true;
module.walk<WalkOrder::PostOrder>([&](Operation *op) {
if (indexed.contains(op) || isa<SpatChannelSendOp, SpatChannelReceiveOp,
SpatSyncOp, SpatWaitOp, SpatHostStoreSyncOp, SpatHostWaitLoadOp, scf::IfOp>(op))
if (Operation *parent = op->getParentOp()) indexed.insert(parent);
});
module.walk([&](Operation *op) {
if (!okay) return WalkResult::interrupt();
if (auto single = dyn_cast<SpatScheduledCompute>(op)) {
auto coreId = op->getAttrOfType<IntegerAttr>("coreId");
if (!coreId) { error = "missing physical core"; okay = false; }
else okay = core(op, coreId.getInt(), 0);
return WalkResult::skip();
}
if (auto batch = dyn_cast<SpatScheduledComputeBatch>(op)) {
auto ids = op->getAttrOfType<DenseI32ArrayAttr>("coreIds");
if (!ids || ids.size() != batch.getLaneCount()) { error = "missing physical batch cores"; okay = false; }
else for (auto [lane, id] : llvm::enumerate(ids.asArrayRef())) if (!(okay = core(op, id, lane))) break;
return WalkResult::skip();
}
return WalkResult::advance();
});
return okay && error.empty();
}
} // namespace
PimPeriodicEstimate onnx_mlir::evaluatePimSpatialSchedule(ModuleOp module,
const PimInstructionTiming &target, PimPeriodicOptions options) try {
if (!target.hasPeriodicTransferTiming() || !target.computeBitwidth)
return unavailableCost("unsupported abstract timing contract");
auto start = std::chrono::steady_clock::now();
Extraction extraction(target, options.workBreakdown, options.omitSynchronization);
bool available = extraction.build(module);
double extractionMs = std::chrono::duration<double, std::milli>(
std::chrono::steady_clock::now() - start).count();
PimPeriodicEstimate estimate;
if (available) estimate = evaluatePimExecution(extraction.program, target, options);
else {
estimate.cost.reason = extraction.error;
estimate.report = llvm::json::Object{{"status", "unavailable"}, {"reason", extraction.error}};
if (options.verifyPeriodicState)
for (auto &recurrence : estimate.cost.recurrence)
recurrence.status = ScheduleRecurrenceEvidence::Unproved;
}
auto &report = estimate.report;
auto &cost = estimate.cost;
cost.timing.extractionSeconds = extractionMs / 1000;
if (available || extraction.loweringSupport == StaticLoweringSupport::Unsupported)
cost.loweringSupport = extraction.loweringSupport;
if (available && options.workBreakdown) {
PimPeriodicOptions sensitivity;
sensitivity.ignoreLocalCopies = true;
auto withoutCopies = analyzePimExecution(extraction.program, target, sensitivity);
if (auto *queue = withoutCopies.getObject("memory_controller"))
report["without_local_copy_work"] = std::move(*queue);
}
auto convergence = cost.convergenceProved();
auto support = cost.loweringSupported();
report["cost_available"] = cost.primary.has_value() && cost.alternative.has_value();
report["convergence_proved"] = convergence
? llvm::json::Value(*convergence) : llvm::json::Value(nullptr);
report["lowering_supported"] = support
? llvm::json::Value(*support) : llvm::json::Value(nullptr);
std::string failureReason = std::move(cost.reason);
cost.reason = "Spatial prediction accuracy has no formal bound";
if (!cost.available()) cost.reason = "Spatial queue cost is unavailable";
else if (cost.loweringSupport != StaticLoweringSupport::Supported)
cost.reason = "Spatial lowering support is unproved";
else if (convergence != true)
cost.reason = "complete-state recurrence is unproved under one or both arbitration policies";
if (!extraction.loweringReason.empty()) cost.reason = extraction.loweringReason;
if (!failureReason.empty()) cost.reason = std::move(failureReason);
report["lowering_support_scope"] = "static operation and transfer contract; final backend verification is required";
if (!extraction.loweringReason.empty()) report["lowering_reason"] = extraction.loweringReason;
report["safe_for_selection"] = false;
report["diagnostic_only"] = true;
report["error_bound_available"] = false;
report["extraction_ms"] = extractionMs;
report["visited_operations"] = extraction.visited;
if (!options.workBreakdown) return estimate;
report["constant_load_sites"] = extraction.constantLoads;
uint64_t workNs = 0, records = 0, constantRequests = 0, constantBytes = 0;
constexpr const char *workClassNames[] = {
"matrix", "vector", "local_copy", "fill", "vector_copy", "scalar_issue"};
std::array<uint64_t, std::size(workClassNames)> workByClass{};
static_assert(Event::ScalarIssue + 1 == std::size(workClassNames));
std::array<uint64_t, 7> counts{};
std::map<uint64_t, uint64_t> readSizes;
std::function<void(const Sequence &, uint64_t)> summarize =
[&](const Sequence &sequence, uint64_t multiplier) {
for (const Event &event : sequence) {
++records;
if (event.kind == Event::Repeat) summarize(event.body, mul(multiplier, event.amount));
else {
counts[event.kind] = add(counts[event.kind], multiplier);
if (event.kind == Event::Work) {
workNs = add(workNs, mul(multiplier, event.amount));
switch (event.workClass) {
case Event::Matrix:
case Event::Vector:
case Event::LocalCopy:
case Event::Fill:
case Event::VectorCopy:
case Event::ScalarIssue:
workByClass[event.workClass] = add(workByClass[event.workClass], mul(multiplier, event.amount));
break;
default: throw pim_timing::Unrepresentable{"unsupported execution work class"};
}
} else if (event.kind == Event::Load) {
readSizes[event.amount] = add(readSizes[event.amount], multiplier);
if (event.constant) {
constantRequests = add(constantRequests, multiplier);
constantBytes = add(constantBytes, mul(multiplier, event.amount));
}
}
}
}
};
for (const Sequence &sequence : extraction.program) summarize(sequence, 1);
report["compute_and_local_work_ns"] = workNs;
llvm::json::Array classes;
for (uint64_t value : workByClass) classes.push_back(value);
llvm::json::Array columns;
for (const char *name : workClassNames) columns.push_back(name);
report["work_class_columns"] = std::move(columns);
report["work_class_ns"] = std::move(classes);
llvm::json::Object eventCounts;
const char *names[] = {"work_chunks", "load", "store", "send", "receive", "sync", "wait"};
for (size_t i = 0; i < counts.size(); ++i) eventCounts[names[i]] = counts[i];
report["event_counts"] = std::move(eventCounts);
report["compact_records"] = records;
report["constant_read_requests"] = constantRequests;
report["constant_read_bytes"] = constantBytes;
llvm::json::Array sizes;
for (auto [bytes, count] : readSizes)
sizes.push_back(llvm::json::Object{{"bytes", bytes}, {"requests", count}});
report["read_sizes"] = std::move(sizes);
llvm::json::Object gaps;
for (const auto &[name, count] : extraction.gaps) gaps[name] = count;
report["unresolved_decisions"] = std::move(gaps);
report["omitted_effects"] = llvm::json::Array{"scalar register setup", "indirect output collection",
"host slice splitting and folding", "copy forwarding and local reuse legality"};
report["analysis_ms"] = std::chrono::duration<double, std::milli>(
std::chrono::steady_clock::now() - start).count();
return estimate;
} catch (const pim_timing::Unrepresentable &failure) {
return unavailableCost(failure.reason);
}
llvm::json::Object onnx_mlir::analyzePimSpatialSchedule(ModuleOp module,
const PimInstructionTiming &target, PimPeriodicOptions options) {
return evaluatePimSpatialSchedule(module, target, options).report;
}
llvm::json::Object onnx_mlir::analyzePimSpatialSynchronizationAblation(ModuleOp module) {
auto timing = getPimInstructionTiming();
auto contract = getPimPeriodicTimingContract();
if (!contract) return unavailableCost(llvm::toString(contract.takeError())).report;
timing.matrixCellBits = *contract;
PimPeriodicOptions options;
options.omitSynchronization = true;
options.verifyPeriodicState = true;
options.measureTime = true;
auto result = evaluatePimSpatialSchedule(module, timing, options);
result.report["diagnostic_only"] = true;
result.report["used_for_selection"] = false;
result.report["cost_model_program"] = "synchronization-omitted";
return std::move(result.report);
}
void onnx_mlir::configurePimScheduleCosts(spatial::SchedulingTarget &target,
PimInstructionTiming timing) {
// The stage-zero entry barrier joins the previous generation's work.
target.estimatePipelineDependencySpan = [](llvm::ArrayRef<Cost> spans) {
return spans.empty() ? Cost{0} : spans.front();
};
auto contract = getPimPeriodicTimingContract();
if (contract) timing.matrixCellBits = *contract;
auto hardware = std::make_shared<const PimInstructionTiming>(std::move(timing));
target.reportPeriodicSchedule = [hardware](const spatial::ComputeGraph &graph,
const spatial::ScheduledComputeMaterializationResult &materialization,
const spatial::DeferredTransferPlan &transfers,
const spatial::DeferredBoundaryPlan &boundaries) {
dumpPeriodicScheduleEstimate(graph, materialization, transfers, boundaries, *hardware);
};
if (!contract) target.wholeScheduleCostUnavailable = llvm::toString(contract.takeError());
if (!hardware->hasPeriodicTransferTiming())
target.wholeScheduleCostUnavailable = "target has no supported queue timing contract";
if (!target.wholeScheduleCostUnavailable.empty()) return;
target.estimateRealizedScheduleCost = [hardware](mlir::ModuleOp module,
llvm::json::Object &summary) {
PimPeriodicOptions options;
options.workBreakdown = pimPeriodicDiagnostics;
options.measureTime = true;
options.verifyPeriodicState = true;
options.searchGuidance = true;
auto estimate = evaluatePimSpatialSchedule(module, *hardware, options);
auto cost = std::move(estimate.cost);
summary = std::move(estimate.report);
if (estimate.queue)
summary["interval_source"] = cost.convergenceProved() == true
? "complete-state recurrence under both arbitration policies"
: "recurrence is unproved under one or both arbitration policies";
summary["cost_available"] = cost.available();
return cost;
};
}