better throughput scheduling with steady state cost model (WIP)
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
#include "llvm/Support/raw_os_ostream.h"
|
||||
#include "llvm/Support/CommandLine.h"
|
||||
|
||||
#include <fstream>
|
||||
|
||||
@@ -6,6 +7,12 @@
|
||||
#include "src/Accelerators/PIM/Common/Support/FileSystemUtils.hpp"
|
||||
|
||||
namespace onnx_mlir {
|
||||
namespace {
|
||||
llvm::cl::opt<bool> dumpIr("pim-dump-ir", llvm::cl::init(false),
|
||||
llvm::cl::desc("Write PIM compiler IR snapshots (large constants are elided)"));
|
||||
}
|
||||
|
||||
bool isPimIrDumpEnabled() { return dumpIr; }
|
||||
|
||||
std::fstream openDialectDumpFileWithExtension(const std::string& name, llvm::StringRef destination, llvm::StringRef extension) {
|
||||
std::string outputDir = getOutputDir();
|
||||
@@ -18,6 +25,7 @@ std::fstream openDialectDumpFileWithExtension(const std::string& name, llvm::Str
|
||||
}
|
||||
|
||||
void dumpModule(mlir::ModuleOp moduleOp, const std::string& name, bool assumeVerified) {
|
||||
if (!dumpIr) return;
|
||||
std::fstream file = openDialectDumpFileWithExtension(name, "/dialects", "mlir");
|
||||
if (!file.is_open())
|
||||
return;
|
||||
|
||||
@@ -11,6 +11,7 @@ namespace onnx_mlir {
|
||||
/// Emits a MLIR snapshot under the current compiler output
|
||||
/// directory for pass-level debugging.
|
||||
void dumpModule(mlir::ModuleOp moduleOp, const std::string& name, bool assumeVerified = false);
|
||||
bool isPimIrDumpEnabled();
|
||||
|
||||
/// Opens a file under the same dialect dump directory used by dumpModule.
|
||||
std::fstream openDialectDumpFileWithExtension(const std::string& name,llvm::StringRef destination = "/dialects", llvm::StringRef extension = "mlir");
|
||||
|
||||
@@ -5,7 +5,14 @@
|
||||
|
||||
namespace onnx_mlir {
|
||||
|
||||
namespace { thread_local bool suppressOutput = false; }
|
||||
ScopedCompilerOutputSuppression::ScopedCompilerOutputSuppression() : previous(suppressOutput) {
|
||||
suppressOutput = true;
|
||||
}
|
||||
ScopedCompilerOutputSuppression::~ScopedCompilerOutputSuppression() { suppressOutput = previous; }
|
||||
|
||||
std::string getOutputDir() {
|
||||
if (suppressOutput) return {};
|
||||
if (outputBaseName.empty() || outputBaseName == "-")
|
||||
return {};
|
||||
|
||||
|
||||
@@ -8,6 +8,15 @@ namespace onnx_mlir {
|
||||
/// current compiler invocation.
|
||||
std::string getOutputDir();
|
||||
|
||||
// Candidate lowering must not emit reports or temporary artifacts.
|
||||
class ScopedCompilerOutputSuppression {
|
||||
public:
|
||||
ScopedCompilerOutputSuppression();
|
||||
~ScopedCompilerOutputSuppression();
|
||||
private:
|
||||
bool previous;
|
||||
};
|
||||
|
||||
void createDirectory(const std::string& directory);
|
||||
|
||||
} // namespace onnx_mlir
|
||||
|
||||
@@ -15,6 +15,9 @@ add_pim_library(OMPimCompilerOptions
|
||||
|
||||
add_pim_library(OMPimCompilerUtils
|
||||
PimCompilerUtils.cpp
|
||||
PimScheduleDiagnostic.cpp
|
||||
PimPeriodicAnalysis.cpp
|
||||
PimPipelineSelection.cpp
|
||||
PimArtifactWriter.cpp
|
||||
PimCodeGen.cpp
|
||||
PimCoreProgram.cpp
|
||||
@@ -42,3 +45,8 @@ add_pim_library(OMPimCompilerUtils
|
||||
ACCEL_INCLUDE_DIRS PRIVATE
|
||||
${PIM_ACCEL_INCLUDE_DIRS}
|
||||
)
|
||||
|
||||
add_onnx_mlir_executable(raptor-periodic NO_INSTALL
|
||||
PimPeriodicDiagnostic.cpp
|
||||
LINK_LIBS PRIVATE OMPimCompilerUtils
|
||||
)
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
#include <absl/types/compare.h>
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <fstream>
|
||||
#include <limits>
|
||||
@@ -41,6 +42,7 @@
|
||||
#include "src/Accelerators/PIM/Common/Support/FileSystemUtils.hpp"
|
||||
#include "src/Accelerators/PIM/Compiler/PimArtifactWriter.hpp"
|
||||
#include "src/Accelerators/PIM/Compiler/PimBinaryFormat.hpp"
|
||||
#include "src/Accelerators/PIM/Compiler/PimPeriodicAnalysis.hpp"
|
||||
#include "src/Accelerators/PIM/Compiler/PimCodeGen.hpp"
|
||||
#include "src/Accelerators/PIM/Compiler/PimCompilerOptions.hpp"
|
||||
#include "src/Accelerators/PIM/Compiler/PimCoreProgram.hpp"
|
||||
@@ -893,6 +895,7 @@ struct CoreEmissionResult {
|
||||
|
||||
OnnxMlirCompilerErrorCodes status = CompilerSuccess;
|
||||
MemoryReportRow reportRow;
|
||||
std::string instructions;
|
||||
llvm::SmallVector<ResolvedWeightView, 8> usedWeights;
|
||||
llvm::SmallVector<DiagnosticRecord, kMaxStoredCodegenDiagnostics> diagnostics;
|
||||
size_t diagnosticCount = 0;
|
||||
@@ -1147,8 +1150,10 @@ static OnnxMlirCompilerErrorCodes emitEmptyCoreArtifacts(StringRef outputDirPath
|
||||
return CompilerSuccess;
|
||||
}
|
||||
|
||||
OnnxMlirCompilerErrorCodes onnx_mlir::compileToPimCode(ModuleOp& moduleOp, std::string& outputDirPath) {
|
||||
if (!outputDirPath.empty()) {
|
||||
OnnxMlirCompilerErrorCodes onnx_mlir::compileToPimCode(ModuleOp& moduleOp, std::string& outputDirPath,
|
||||
PimInstructionProgram *instructions, PimCodegenTiming *timing) {
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
if (!instructions && !outputDirPath.empty()) {
|
||||
if (auto error = sys::fs::create_directory(outputDirPath)) {
|
||||
errs() << "Error creating output directory: " << outputDirPath << ": " << error.message() << '\n';
|
||||
return InvalidOutputFileAccess;
|
||||
@@ -1164,8 +1169,9 @@ OnnxMlirCompilerErrorCodes onnx_mlir::compileToPimCode(ModuleOp& moduleOp, std::
|
||||
memory.hostMem.allocateHost(moduleOp, funcOp);
|
||||
memory.reportHost();
|
||||
|
||||
if (auto err = writeMemoryBinary(moduleOp, funcOp, memory, outputDirPath))
|
||||
return err;
|
||||
if (!instructions)
|
||||
if (auto err = writeMemoryBinary(moduleOp, funcOp, memory, outputDirPath))
|
||||
return err;
|
||||
|
||||
json::Object xbarsPerArrayGroup;
|
||||
size_t maxCoreId = 0;
|
||||
@@ -1295,15 +1301,22 @@ OnnxMlirCompilerErrorCodes onnx_mlir::compileToPimCode(ModuleOp& moduleOp, std::
|
||||
|
||||
std::error_code errorCode;
|
||||
auto outputCorePath = outputDirPath + "/core_" + std::to_string(job.physicalCoreId) + ".pim";
|
||||
raw_fd_ostream coreBinaryStream(outputCorePath, errorCode, sys::fs::OF_None);
|
||||
if (errorCode) {
|
||||
errs() << "Error while opening core file `" << outputCorePath << "`: " << errorCode.message() << '\n';
|
||||
result.status = InvalidOutputFileAccess;
|
||||
return result;
|
||||
llvm::SmallVector<char, 0> binary;
|
||||
raw_svector_ostream memoryStream(binary);
|
||||
std::unique_ptr<raw_fd_ostream> fileStream;
|
||||
if (!instructions) {
|
||||
fileStream = std::make_unique<raw_fd_ostream>(outputCorePath, errorCode, sys::fs::OF_None);
|
||||
if (errorCode) {
|
||||
errs() << "Error opening core file: " << outputCorePath << ": " << errorCode.message() << '\n';
|
||||
result.status = InvalidOutputFileAccess;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
raw_pwrite_stream &coreBinaryStream = instructions
|
||||
? static_cast<raw_pwrite_stream &>(memoryStream) : *fileStream;
|
||||
|
||||
std::unique_ptr<raw_fd_ostream> coreJsonStream;
|
||||
if (pimEmitJson.getValue()) {
|
||||
if (!instructions && pimEmitJson.getValue()) {
|
||||
std::string outputCoreJsonPath = outputDirPath + "/core_" + std::to_string(job.physicalCoreId) + ".json";
|
||||
errorCode = std::error_code();
|
||||
coreJsonStream = std::make_unique<raw_fd_ostream>(outputCoreJsonPath, errorCode);
|
||||
@@ -1319,10 +1332,11 @@ OnnxMlirCompilerErrorCodes onnx_mlir::compileToPimCode(ModuleOp& moduleOp, std::
|
||||
PimCodeGen coreCodeGen(jobMemory, instructionWriter, coreJsonStream.get());
|
||||
auto finalizeInstructions = [&]() {
|
||||
bool succeeded = mlir::succeeded(instructionWriter.finalize());
|
||||
coreBinaryStream.close();
|
||||
if (coreBinaryStream.has_error()) {
|
||||
coreBinaryStream.clear_error();
|
||||
succeeded = false;
|
||||
if (fileStream) {
|
||||
fileStream->close();
|
||||
if (fileStream->has_error()) { fileStream->clear_error(); succeeded = false; }
|
||||
} else {
|
||||
result.instructions.assign(binary.begin(), binary.end());
|
||||
}
|
||||
return succeeded;
|
||||
};
|
||||
@@ -1376,8 +1390,14 @@ OnnxMlirCompilerErrorCodes onnx_mlir::compileToPimCode(ModuleOp& moduleOp, std::
|
||||
};
|
||||
|
||||
std::vector<CoreEmissionResult> jobResults(jobs.size());
|
||||
auto emissionStart = std::chrono::steady_clock::now();
|
||||
if (timing)
|
||||
timing->preparationSeconds = std::chrono::duration<double>(emissionStart - start).count();
|
||||
mlir::parallelFor(
|
||||
moduleOp.getContext(), 0, jobs.size(), [&](size_t index) { jobResults[index] = emitJob(jobs[index]); });
|
||||
if (timing)
|
||||
timing->emissionSeconds = std::chrono::duration<double>(
|
||||
std::chrono::steady_clock::now() - emissionStart).count();
|
||||
|
||||
pim::CappedDiagnosticReporter diagnostics;
|
||||
Operation* summaryAnchor = nullptr;
|
||||
@@ -1407,14 +1427,33 @@ OnnxMlirCompilerErrorCodes onnx_mlir::compileToPimCode(ModuleOp& moduleOp, std::
|
||||
physicalCoreId < activePhysicalCores.size(); ++physicalCoreId) {
|
||||
if (activePhysicalCores[physicalCoreId])
|
||||
continue;
|
||||
if (auto err =
|
||||
emitEmptyCoreArtifacts(outputDirPath, physicalCoreId))
|
||||
return err;
|
||||
if (!instructions)
|
||||
if (auto err = emitEmptyCoreArtifacts(outputDirPath, physicalCoreId))
|
||||
return err;
|
||||
xbarsPerArrayGroup["core" + std::to_string(physicalCoreId)] =
|
||||
json::Array {};
|
||||
memory.recordCoreReport(physicalCoreId, MemoryReportRow {});
|
||||
}
|
||||
|
||||
if (instructions) {
|
||||
instructions->instructions.resize(maxPhysicalCoreId + 1);
|
||||
instructions->arrayGroups.resize(maxPhysicalCoreId + 1);
|
||||
for (size_t core = 0; core <= maxPhysicalCoreId; ++core) {
|
||||
instructions->arrayGroups[core].clear();
|
||||
llvm::SmallVector<char> empty;
|
||||
raw_svector_ostream stream(empty);
|
||||
pim_binary::writeHeader(stream);
|
||||
instructions->instructions[core].assign(empty.begin(), empty.end());
|
||||
}
|
||||
for (size_t i = 0; i < jobs.size(); ++i) {
|
||||
size_t core = jobs[i].physicalCoreId;
|
||||
instructions->instructions[core] = std::move(jobResults[i].instructions);
|
||||
for (const auto &weight : jobResults[i].usedWeights)
|
||||
instructions->arrayGroups[core].push_back(weight.shape[1] / crossbarSize.getValue());
|
||||
}
|
||||
return CompilerSuccess;
|
||||
}
|
||||
|
||||
llvm::SmallVector<WeightFileRequest, 8> weightRequests;
|
||||
weightRequests.reserve(jobs.size());
|
||||
for (size_t jobIndex = 0; jobIndex < jobs.size(); ++jobIndex) {
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
namespace onnx_mlir {
|
||||
|
||||
struct CompiledCoreProgram;
|
||||
struct PimInstructionProgram;
|
||||
class PimInstructionWriter;
|
||||
|
||||
struct MemEntry {
|
||||
@@ -226,7 +227,13 @@ public:
|
||||
|
||||
};
|
||||
|
||||
OnnxMlirCompilerErrorCodes compileToPimCode(mlir::ModuleOp& moduleOpRef, std::string& outputDirName);
|
||||
struct PimCodegenTiming {
|
||||
double preparationSeconds = 0;
|
||||
double emissionSeconds = 0;
|
||||
};
|
||||
|
||||
OnnxMlirCompilerErrorCodes compileToPimCode(mlir::ModuleOp& moduleOpRef, std::string& outputDirName,
|
||||
PimInstructionProgram *instructions = nullptr, PimCodegenTiming *timing = nullptr);
|
||||
|
||||
} // namespace onnx_mlir
|
||||
|
||||
|
||||
@@ -89,6 +89,10 @@ llvm::cl::opt<bool> pimReportConvLowering("pim-report-conv-lowering",
|
||||
llvm::cl::init(true),
|
||||
llvm::cl::cat(OnnxMlirOptions));
|
||||
|
||||
llvm::cl::opt<bool> pimPeriodicDiagnostics("pim-periodic-diagnostics",
|
||||
llvm::cl::desc("Emit the optional pre-codegen recurrence timing report"),
|
||||
llvm::cl::init(false), llvm::cl::cat(OnnxMlirOptions));
|
||||
|
||||
llvm::cl::opt<bool> pimEmitJson("pim-emit-json",
|
||||
llvm::cl::desc("Also emit per-core JSON instruction files alongside binary .pim files"),
|
||||
llvm::cl::init(false),
|
||||
|
||||
@@ -56,6 +56,7 @@ extern llvm::cl::opt<PimSpatialDataflowExportType> pimExportSpatialDataflow;
|
||||
|
||||
extern llvm::cl::opt<bool> pimOnlyCodegen;
|
||||
extern llvm::cl::opt<bool> pimEmitJson;
|
||||
extern llvm::cl::opt<bool> pimPeriodicDiagnostics;
|
||||
extern llvm::cl::opt<bool> pimReportConvLowering;
|
||||
extern llvm::cl::opt<bool> pimDetectCommunicationDeadlock;
|
||||
extern llvm::cl::opt<bool> pimVerifyBufferizationCopyFreedom;
|
||||
|
||||
@@ -14,6 +14,9 @@
|
||||
|
||||
#include "src/Accelerators/PIM/Common/PimCommon.hpp"
|
||||
#include "src/Accelerators/PIM/Compiler/PimCompilerOptions.hpp"
|
||||
#include "PimPipelineSelection.hpp"
|
||||
#include "PimInstructionTiming.hpp"
|
||||
#include "PimPeriodicAnalysis.hpp"
|
||||
#include "src/Accelerators/PIM/Compiler/PimCompilerUtils.hpp"
|
||||
#include "src/Accelerators/PIM/Conversion/ONNXToSpatial/ONNXToSpatialOptions.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Pim/PimOps.hpp"
|
||||
@@ -174,8 +177,9 @@ std::pair<size_t, size_t> getConfigPair(const llvm::json::Object& object,
|
||||
}
|
||||
|
||||
void loadPimInterProcessorLatencies(
|
||||
spatial::SchedulingTarget& target,
|
||||
const llvm::json::Object& network) {
|
||||
PimInstructionTiming& target,
|
||||
const llvm::json::Object& network,
|
||||
std::optional<int64_t> memorySwitch) {
|
||||
std::optional<llvm::StringRef> filename =
|
||||
network.getString("net_config_file_path");
|
||||
if (!filename)
|
||||
@@ -240,10 +244,29 @@ void loadPimInterProcessorLatencies(
|
||||
? 0
|
||||
: (latencySum + static_cast<Cost>(pairCount) - 1)
|
||||
/ static_cast<Cost>(pairCount);
|
||||
if (memorySwitch) {
|
||||
const auto *memoryRow = latencies->getObject(std::to_string(*memorySwitch));
|
||||
for (size_t core = 0; core < target.processorCount; ++core) {
|
||||
const auto *row = latencies->getObject(std::to_string(core));
|
||||
auto request = row ? row->getNumber(std::to_string(*memorySwitch)) : std::nullopt;
|
||||
auto response = memoryRow ? memoryRow->getNumber(std::to_string(core)) : std::nullopt;
|
||||
if (!request || !response || !std::isfinite(*request)
|
||||
|| !std::isfinite(*response) || *request < 0 || *response < 0
|
||||
|| *request >= static_cast<double>(std::numeric_limits<Cost>::max())
|
||||
|| *response >= static_cast<double>(std::numeric_limits<Cost>::max())) {
|
||||
target.sharedMemoryRequestLatencyNs.clear();
|
||||
target.sharedMemoryResponseLatencyNs.clear();
|
||||
break;
|
||||
}
|
||||
target.sharedMemoryRequestLatencyNs.push_back(std::ceil(*request));
|
||||
target.sharedMemoryResponseLatencyNs.push_back(std::ceil(*response));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
spatial::SchedulingTarget getPimSchedulingTarget() {
|
||||
spatial::SchedulingTarget target = getDefaultPimSchedulingTarget();
|
||||
PimInstructionTiming loadPimInstructionTiming() {
|
||||
PimInstructionTiming target;
|
||||
static_cast<spatial::SchedulingTarget &>(target) = getDefaultPimSchedulingTarget();
|
||||
if (pimTargetConfig.empty())
|
||||
return target;
|
||||
|
||||
@@ -298,12 +321,19 @@ spatial::SchedulingTarget getPimSchedulingTarget() {
|
||||
|| target.matrixColumns != crossbarSize.getValue())
|
||||
llvm::report_fatal_error("Pim target config resources do not match --core-count, "
|
||||
"--crossbar-count, and --crossbar-size");
|
||||
loadPimInterProcessorLatencies(target, network);
|
||||
loadPimInterProcessorLatencies(target, network,
|
||||
core.getInteger("global_memory_switch_id"));
|
||||
|
||||
target.processorPeriodNs =
|
||||
getConfigCost(core, "period", target.processorPeriodNs);
|
||||
target.signalIssueNs = target.processorPeriodNs;
|
||||
target.controlMessageBytes = 1;
|
||||
target.sharedMemoryReadReturnsPayload = false;
|
||||
target.peerPermissionThenSourceRead = true;
|
||||
target.localMemoryWidthBytes =
|
||||
getConfigCost(localMemory, "data_width", target.localMemoryWidthBytes);
|
||||
target.localMemoryPeriodNs =
|
||||
getConfigCost(localMemory, "period", target.localMemoryPeriodNs);
|
||||
target.localMemoryReadLatencyCycles =
|
||||
getConfigCost(localMemory, "read_latency_cycle", target.localMemoryReadLatencyCycles);
|
||||
target.localMemoryWriteLatencyCycles =
|
||||
@@ -345,6 +375,65 @@ spatial::SchedulingTarget getPimSchedulingTarget() {
|
||||
|
||||
} // namespace
|
||||
|
||||
PimInstructionTiming getPimInstructionTiming() {
|
||||
return loadPimInstructionTiming();
|
||||
}
|
||||
|
||||
spatial::SchedulingTarget getPimSchedulingTarget() {
|
||||
auto timing = getPimInstructionTiming();
|
||||
auto target = static_cast<spatial::SchedulingTarget>(timing);
|
||||
configurePimScheduleCosts(target, std::move(timing));
|
||||
return target;
|
||||
}
|
||||
|
||||
llvm::Expected<int64_t> getPimPeriodicTimingContract() {
|
||||
auto buffer = llvm::MemoryBuffer::getFile(pimTargetConfig);
|
||||
if (!buffer) return llvm::createStringError("queue selection requires --pim-target-config with instruction timing");
|
||||
auto parsed = llvm::json::parse(buffer.get()->getBuffer());
|
||||
if (!parsed) return parsed.takeError();
|
||||
const auto *root = parsed->getAsObject();
|
||||
const auto *chip = root ? root->getObject("chip_config") : nullptr;
|
||||
const auto *core = chip ? chip->getObject("core_config") : nullptr;
|
||||
const auto *matrix = core ? core->getObject("matrix_config") : nullptr;
|
||||
if (!matrix || core->getInteger("rob_size").value_or(1) != 1)
|
||||
return llvm::createStringError("queue selection requires a target with ROB capacity one and matrix timing");
|
||||
auto bits = matrix->getInteger("cell_precision").value_or(2);
|
||||
if (bits <= 0) return llvm::createStringError("matrix cell precision must be positive");
|
||||
return bits;
|
||||
}
|
||||
|
||||
void addPimLoweringPasses(PassManager &pm,
|
||||
const spatial::SpatialTargetResources &targetResources, PimEmissionTargetType target,
|
||||
bool reportProgress) {
|
||||
auto message = [&](llvm::StringRef text) {
|
||||
if (reportProgress) pm.addPass(createMessagePass(text.str()));
|
||||
};
|
||||
if (target >= EmitPim) {
|
||||
pm.addPass(createSpatialToPimPass(targetResources));
|
||||
message("Spatial lowered to Pim");
|
||||
}
|
||||
|
||||
if (target >= EmitPimBufferized) {
|
||||
pm.addPass(createPimBufferizationPreparationPass(pimVerifyBufferizationCopyFreedom.getValue()));
|
||||
pm.addPass(createPimOneShotBufferizationPass());
|
||||
pm.addPass(createPimMemoryNormalizationPass());
|
||||
pm.addPass(createPimBufferizationVerificationPass());
|
||||
message("Pim bufferized");
|
||||
}
|
||||
|
||||
if (target >= EmitPimCodegen) {
|
||||
pm.addPass(mlir::createLowerAffinePass());
|
||||
pm.addPass(createPimHostConstantFoldingPass());
|
||||
message("Pim host constants folded");
|
||||
pm.addPass(createPimInstructionSelectionPass());
|
||||
message("Pim instructions selected");
|
||||
pm.addPass(createPimLocalMemoryPlanningPass());
|
||||
message("Pim local memory planned");
|
||||
pm.addPass(createPimVerificationPass(targetResources, pimDetectCommunicationDeadlock.getValue()));
|
||||
message("Pim verified");
|
||||
}
|
||||
}
|
||||
|
||||
void addPassesPim(OwningOpRef<ModuleOp>& module,
|
||||
PassManager& pm,
|
||||
EmissionTargetType& emissionTarget,
|
||||
@@ -374,34 +463,22 @@ void addPassesPim(OwningOpRef<ModuleOp>& module,
|
||||
pm.addPass(createLowerSpatialPlansPass(targetResources, planningOptions, exportStage));
|
||||
pm.addPass(createTrivialGraphComputeMergePass(
|
||||
schedulingTarget.residentWeightCapacity, exportStage));
|
||||
pm.addPass(spatial::createScheduleAndRealizeSpatialPass(
|
||||
schedulingTarget, exportStage, pipelineStages.getValue()));
|
||||
if (pipelineStages.getValue() > 1 && pimEmissionTarget >= EmitPimCodegen) {
|
||||
pm.addPass(createPimPipelineSelectionPass(schedulingTarget, targetResources,
|
||||
pipelineStages.getValue(), exportStage));
|
||||
pm.addPass(createEmitPimCodePass());
|
||||
return;
|
||||
} else {
|
||||
if (pipelineStages.getValue() > 1)
|
||||
pm.addPass(createMessagePass("Queue-aware pipeline: intermediate emission retains the original schedule without backend evaluation"));
|
||||
pm.addPass(spatial::createScheduleAndRealizeSpatialPass(
|
||||
schedulingTarget, exportStage, pipelineStages.getValue(), pimPeriodicDiagnostics.getValue()));
|
||||
}
|
||||
pm.addPass(createMessagePass("Onnx lowered to Spatial"));
|
||||
}
|
||||
|
||||
if (pimEmissionTarget >= EmitPim) {
|
||||
pm.addPass(createSpatialToPimPass(targetResources));
|
||||
pm.addPass(createMessagePass("Spatial lowered to Pim"));
|
||||
}
|
||||
|
||||
if (pimEmissionTarget >= EmitPimBufferized) {
|
||||
pm.addPass(createPimBufferizationPreparationPass(pimVerifyBufferizationCopyFreedom.getValue()));
|
||||
pm.addPass(createPimOneShotBufferizationPass());
|
||||
pm.addPass(createPimMemoryNormalizationPass());
|
||||
pm.addPass(createPimBufferizationVerificationPass());
|
||||
pm.addPass(createMessagePass("Pim bufferized"));
|
||||
}
|
||||
|
||||
addPimLoweringPasses(pm, targetResources, pimEmissionTarget);
|
||||
if (pimEmissionTarget >= EmitPimCodegen) {
|
||||
pm.addPass(mlir::createLowerAffinePass());
|
||||
pm.addPass(createPimHostConstantFoldingPass());
|
||||
pm.addPass(createMessagePass("Pim host constants folded"));
|
||||
pm.addPass(createPimInstructionSelectionPass());
|
||||
pm.addPass(createMessagePass("Pim instructions selected"));
|
||||
pm.addPass(createPimLocalMemoryPlanningPass());
|
||||
pm.addPass(createMessagePass("Pim local memory planned"));
|
||||
pm.addPass(createPimVerificationPass(targetResources, pimDetectCommunicationDeadlock.getValue()));
|
||||
pm.addPass(createMessagePass("Pim verified"));
|
||||
pm.addPass(createEmitPimCodePass());
|
||||
pm.addPass(createMessagePass("Pim code emitted"));
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include "PimCompilerOptions.hpp"
|
||||
#include "mlir/IR/BuiltinOps.h"
|
||||
#include "llvm/Support/Error.h"
|
||||
#include "mlir/Pass/PassManager.h"
|
||||
#include "mlir/Pass/PassRegistry.h"
|
||||
|
||||
@@ -8,6 +10,16 @@
|
||||
|
||||
namespace onnx_mlir {
|
||||
|
||||
namespace spatial { struct SchedulingTarget; struct SpatialTargetResources; }
|
||||
spatial::SchedulingTarget getPimSchedulingTarget();
|
||||
struct PimInstructionTiming;
|
||||
PimInstructionTiming getPimInstructionTiming();
|
||||
llvm::Expected<int64_t> getPimPeriodicTimingContract();
|
||||
|
||||
void addPimLoweringPasses(mlir::PassManager &pm,
|
||||
const spatial::SpatialTargetResources &resources, PimEmissionTargetType target,
|
||||
bool reportProgress = true);
|
||||
|
||||
void addPassesPim(mlir::OwningOpRef<mlir::ModuleOp>& module,
|
||||
mlir::PassManager& pm,
|
||||
EmissionTargetType& emissionTarget,
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
#pragma once
|
||||
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/SchedulingTarget.hpp"
|
||||
|
||||
namespace onnx_mlir {
|
||||
|
||||
// PIM transport and instruction timing. Spatial consumes only the base costs.
|
||||
struct PimInstructionTiming : spatial::SchedulingTarget {
|
||||
bool peerPermissionThenSourceRead = false;
|
||||
Cost signalIssueNs = 0;
|
||||
Cost controlMessageBytes = 0;
|
||||
bool sharedMemoryReadReturnsPayload = true;
|
||||
std::vector<Cost> sharedMemoryRequestLatencyNs;
|
||||
std::vector<Cost> sharedMemoryResponseLatencyNs;
|
||||
|
||||
bool hasPeriodicTransferTiming() const {
|
||||
return processorCount && sharedMemoryWidthBytes && controlMessageBytes
|
||||
&& peerPermissionThenSourceRead
|
||||
&& sharedMemoryRequestLatencyNs.size() == processorCount
|
||||
&& sharedMemoryResponseLatencyNs.size() == processorCount
|
||||
&& interProcessorLatencyNs.size() == processorCount * processorCount
|
||||
&& localMemoryWidthBytes && transferWidthBytes;
|
||||
}
|
||||
|
||||
Cost getLinkServiceNs(Cost bytes, size_t source, size_t destination) const {
|
||||
Cost flits = bytes / transferWidthBytes + (bytes % transferWidthBytes != 0);
|
||||
return checkedMultiply(flits,
|
||||
getInterProcessorLatencyNs(source, destination));
|
||||
}
|
||||
|
||||
Cost getSharedMemoryLinkServiceNs(Cost bytes, size_t core, bool response) const {
|
||||
Cost flits = bytes / transferWidthBytes + (bytes % transferWidthBytes != 0);
|
||||
return checkedMultiply(flits, response ? sharedMemoryResponseLatencyNs[core]
|
||||
: sharedMemoryRequestLatencyNs[core]);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
} // namespace onnx_mlir
|
||||
@@ -0,0 +1,671 @@
|
||||
#include "PimPeriodicAnalysis.hpp"
|
||||
#include "PimInstructionTiming.hpp"
|
||||
#include "PimCodeGen.hpp"
|
||||
#include "PimCompilerUtils.hpp"
|
||||
#include "PimCompilerOptions.hpp"
|
||||
#include "PimScheduleDiagnostic.hpp"
|
||||
#include "llvm/Support/SHA256.h"
|
||||
#include "llvm/ADT/StringExtras.h"
|
||||
#include <chrono>
|
||||
#include "PimBinaryFormat.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/PeriodicDependencies.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/SchedulingTarget.hpp"
|
||||
|
||||
#include "llvm/ADT/SmallVector.h"
|
||||
#include <array>
|
||||
#include <map>
|
||||
#include <limits>
|
||||
#include <queue>
|
||||
#include <cmath>
|
||||
|
||||
using namespace onnx_mlir;
|
||||
using namespace onnx_mlir::spatial;
|
||||
using Opcode = pim_binary::Opcode;
|
||||
namespace {
|
||||
using Key = std::pair<int64_t, int64_t>;
|
||||
struct Event { int64_t core; uint32_t pc; llvm::StringRef kind; };
|
||||
struct Send { size_t enqueue, requestArrival, payloadArrival; Cost bytes; };
|
||||
struct Receive { size_t complete, permissionArrival, permissionDispatch; Cost bytes; };
|
||||
struct Request { size_t begin, arrival; };
|
||||
struct Notice { size_t arrival; int64_t source; };
|
||||
struct Wait { size_t end; int64_t expected; };
|
||||
struct Core {
|
||||
size_t entry, tail, firstNetwork, lastNetwork;
|
||||
Cost pending = 0, work = 0, instructions = 0;
|
||||
std::array<Cost, 7> service{};
|
||||
bool blockingNetworkInChunk = false;
|
||||
};
|
||||
constexpr size_t absent = std::numeric_limits<size_t>::max();
|
||||
|
||||
llvm::json::Object estimateQueuedPeriod(const std::vector<Event> &events,
|
||||
const std::vector<PeriodicDependency> &edges,
|
||||
const std::vector<std::pair<size_t, Cost>> &services, const std::map<int64_t, Core> &cores,
|
||||
bool reverseTies) {
|
||||
struct Node {
|
||||
llvm::SmallVector<size_t, 2> incoming, outgoing;
|
||||
size_t completed = 0, readyInputs = 0;
|
||||
bool busy = false;
|
||||
};
|
||||
struct Pending {
|
||||
Cost time;
|
||||
size_t node;
|
||||
bool arrival;
|
||||
};
|
||||
struct Tokens {
|
||||
llvm::SmallVector<Cost, 1> values;
|
||||
size_t head = 0;
|
||||
};
|
||||
auto later = [reverseTies](const Pending &a, const Pending &b) {
|
||||
if (a.time != b.time) return a.time > b.time;
|
||||
return reverseTies ? a.node < b.node : a.node > b.node;
|
||||
};
|
||||
std::vector<Node> nodes(events.size());
|
||||
std::vector<Tokens> tokens(edges.size());
|
||||
std::vector<Cost> service(events.size(), 0);
|
||||
std::vector<bool> memoryAccess(events.size(), false);
|
||||
std::vector<bool> entries(events.size(), false);
|
||||
for (auto [node, cost] : services) {
|
||||
service[node] = cost;
|
||||
memoryAccess[node] = true;
|
||||
}
|
||||
for (const auto &[core, state] : cores) entries[state.entry] = true;
|
||||
for (auto [index, edge] : llvm::enumerate(edges)) {
|
||||
nodes[edge.source].outgoing.push_back(index);
|
||||
nodes[edge.target].incoming.push_back(index);
|
||||
tokens[index].values.assign(edge.distance, 0);
|
||||
nodes[edge.target].readyInputs += edge.distance != 0;
|
||||
}
|
||||
std::priority_queue<Pending, std::vector<Pending>, decltype(later)> pending(later);
|
||||
auto schedule = [&](size_t node) {
|
||||
auto &state = nodes[node];
|
||||
if (state.busy || state.readyInputs != state.incoming.size()) return;
|
||||
Cost time = 0;
|
||||
for (size_t edge : state.incoming) {
|
||||
auto &queue = tokens[edge];
|
||||
time = std::max(time, queue.values[queue.head++]);
|
||||
if (queue.head == queue.values.size()) {
|
||||
queue.values.clear(); queue.head = 0; --state.readyInputs;
|
||||
} else if (queue.head * 2 >= queue.values.size()) {
|
||||
queue.values.erase(queue.values.begin(), queue.values.begin() + queue.head);
|
||||
queue.head = 0;
|
||||
}
|
||||
}
|
||||
state.busy = true;
|
||||
pending.push({time - service[node], node, memoryAccess[node]});
|
||||
};
|
||||
for (size_t node = 0; node < nodes.size(); ++node) schedule(node);
|
||||
constexpr size_t maximumRounds = 64;
|
||||
std::array<Cost, maximumRounds> roundEnd{};
|
||||
std::array<size_t, maximumRounds> roundCount{};
|
||||
std::map<int64_t, std::array<Cost, maximumRounds>> queueWait;
|
||||
Cost available = 0;
|
||||
Cost maximumQueueWait = 0;
|
||||
size_t maximumQueueNode = 0;
|
||||
size_t processed = 0;
|
||||
const size_t budget = 16 * (events.size() + edges.size());
|
||||
llvm::json::Object result{{"status", "unavailable"}};
|
||||
while (!pending.empty() && processed++ < budget) {
|
||||
auto next = pending.top(); pending.pop();
|
||||
auto &node = nodes[next.node];
|
||||
if (node.completed >= maximumRounds) {
|
||||
result["reason"] = "queue diagnostic exceeded its per-event generation bound";
|
||||
return result;
|
||||
}
|
||||
if (next.arrival) {
|
||||
Cost begin = std::max(available, next.time);
|
||||
if (begin - next.time > maximumQueueWait) {
|
||||
maximumQueueWait = begin - next.time;
|
||||
maximumQueueNode = next.node;
|
||||
}
|
||||
queueWait[events[next.node].core][node.completed] += begin - next.time;
|
||||
available = begin + service[next.node];
|
||||
pending.push({available, next.node, false});
|
||||
continue;
|
||||
}
|
||||
++node.completed;
|
||||
node.busy = false;
|
||||
if (entries[next.node]) {
|
||||
size_t round = node.completed - 1;
|
||||
roundEnd[round] = std::max(roundEnd[round], next.time);
|
||||
if (++roundCount[round] == cores.size() && round >= 4 && round % 2 == 0) {
|
||||
Cost first = roundEnd[round - 2] - roundEnd[round - 4];
|
||||
Cost second = roundEnd[round] - roundEnd[round - 2];
|
||||
Cost maximum = std::max(first, second);
|
||||
if (maximum && std::abs(static_cast<double>(first) - second) <= maximum * 0.01) {
|
||||
result["status"] = "estimated";
|
||||
result["interval_ns"] = (roundEnd[round] - roundEnd[round - 4]) / 4.0;
|
||||
result["completed_generations"] = static_cast<int64_t>(round);
|
||||
result["processed_events"] = static_cast<int64_t>(processed);
|
||||
result["maximum_queue_wait_ns_including_bootstrap"] = static_cast<int64_t>(maximumQueueWait);
|
||||
if (maximumQueueWait) {
|
||||
result["maximum_queue_core"] = events[maximumQueueNode].core;
|
||||
result["maximum_queue_pc"] = events[maximumQueueNode].pc;
|
||||
}
|
||||
llvm::json::Array waits;
|
||||
for (const auto &[core, values] : queueWait) {
|
||||
Cost wait = 0;
|
||||
for (size_t generation = round - 4; generation < round; ++generation)
|
||||
wait += values[generation];
|
||||
waits.push_back(llvm::json::Object{{"core", core}, {"queue_wait_ns", wait / 4.0}});
|
||||
}
|
||||
result["per_core"] = std::move(waits);
|
||||
result["tie_policy"] = reverseTies ? "reverse event-index order for simultaneous readiness"
|
||||
: "event-index order for simultaneous readiness";
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (size_t edge : node.outgoing) {
|
||||
if (tokens[edge].values.empty()) ++nodes[edges[edge].target].readyInputs;
|
||||
tokens[edge].values.push_back(next.time + edges[edge].delayNs);
|
||||
schedule(edges[edge].target);
|
||||
}
|
||||
schedule(next.node);
|
||||
}
|
||||
result["reason"] = "queue diagnostic did not converge within its event budget";
|
||||
return result;
|
||||
}
|
||||
|
||||
class Analysis {
|
||||
public:
|
||||
PimInstructionTiming target;
|
||||
PimPeriodicOptions options;
|
||||
bool queues = true, issue = true, memoryQueue = false;
|
||||
Cost cellBits;
|
||||
std::vector<Event> events;
|
||||
std::vector<PeriodicDependency> edges;
|
||||
std::map<int64_t, Core> cores;
|
||||
SharedMemoryDemand memory;
|
||||
std::vector<std::pair<size_t, Cost>> memoryServices;
|
||||
std::array<Cost, pim_binary::kOpcodeCount> opcodeService{}, opcodeCounts{};
|
||||
std::string error;
|
||||
|
||||
bool readCore(int64_t core, llvm::StringRef data, const llvm::json::Array &groups);
|
||||
llvm::json::Object queueReport();
|
||||
bool connect();
|
||||
llvm::json::Object report();
|
||||
|
||||
private:
|
||||
std::map<Key, std::vector<Send>> sends;
|
||||
std::map<Key, std::vector<Receive>> receives;
|
||||
std::map<Key, std::vector<Notice>> signals;
|
||||
std::map<Key, Wait> waits;
|
||||
size_t event(int64_t core, uint32_t pc, llvm::StringRef kind) {
|
||||
events.push_back({core, pc, kind});
|
||||
return events.size() - 1;
|
||||
}
|
||||
size_t append(int64_t core, uint32_t pc, llvm::StringRef kind, Cost delay = 0) {
|
||||
size_t next = event(core, pc, kind);
|
||||
Core &state = cores.at(core);
|
||||
edges.push_back({state.tail, next, delay, 0});
|
||||
state.tail = next;
|
||||
return next;
|
||||
}
|
||||
void flush(int64_t core, uint32_t pc) {
|
||||
Core &state = cores.at(core);
|
||||
if (state.pending) {
|
||||
append(core, pc, "local-work", state.pending);
|
||||
state.work += state.pending;
|
||||
state.pending = 0;
|
||||
}
|
||||
if (state.blockingNetworkInChunk)
|
||||
state.lastNetwork = state.tail;
|
||||
state.blockingNetworkInChunk = false;
|
||||
}
|
||||
Request network(int64_t core, uint32_t pc, size_t ready,
|
||||
Cost latency, Cost hold = 0) {
|
||||
Core &state = cores.at(core);
|
||||
size_t begin = event(core, pc, "fifo-dispatch"), arrival = event(core, pc, "delivery");
|
||||
size_t end = hold ? event(core, pc, "switch-release") : arrival;
|
||||
edges.push_back({ready, begin, 0, 0});
|
||||
if (queues && state.lastNetwork != absent)
|
||||
edges.push_back({state.lastNetwork, begin, 0, 0});
|
||||
edges.push_back({begin, arrival, latency, 0});
|
||||
if (hold)
|
||||
edges.push_back({arrival, end, hold, 0});
|
||||
if (state.firstNetwork == absent)
|
||||
state.firstNetwork = begin;
|
||||
state.lastNetwork = end;
|
||||
return {begin, arrival};
|
||||
}
|
||||
Cost local(Cost bytes, bool write) const {
|
||||
return target.getLocalMemoryServiceNs(bytes, write);
|
||||
}
|
||||
Cost retirement(bool matrix = false) const {
|
||||
// Completion can join the current clock edge before ClockDomain runs.
|
||||
// ROB retirement needs another edge; matrix also has AG/commit registers.
|
||||
return issue ? (matrix ? 3 : 1) * target.processorPeriodNs : 0;
|
||||
}
|
||||
bool communication(int64_t core, uint32_t pc, Opcode op,
|
||||
int32_t peer, int32_t reg, int32_t count, Cost bytes);
|
||||
};
|
||||
|
||||
bool Analysis::communication(int64_t core, uint32_t pc, Opcode op,
|
||||
int32_t peer, int32_t reg, int32_t count, Cost bytes) {
|
||||
flush(core, pc);
|
||||
size_t begin = append(core, pc, "communication");
|
||||
if (op == Opcode::sync) {
|
||||
if (peer < 0 || peer >= static_cast<int64_t>(target.processorCount)
|
||||
|| reg < 0 || reg >= static_cast<int64_t>(target.synchronizationRegisterCount)) {
|
||||
error = "SYNC has an invalid core or event register";
|
||||
return false;
|
||||
}
|
||||
auto request = network(core, pc, begin,
|
||||
target.getLinkServiceNs(target.controlMessageBytes, core, peer));
|
||||
signals[{peer, reg}].push_back({request.arrival, core});
|
||||
append(core, pc, "sync-complete", target.signalIssueNs + retirement());
|
||||
cores.at(core).work += target.signalIssueNs + retirement();
|
||||
cores.at(core).service[6] += target.signalIssueNs + retirement();
|
||||
opcodeService[static_cast<unsigned>(op)] += target.signalIssueNs + retirement();
|
||||
} else if (op == Opcode::wait) {
|
||||
size_t end = append(core, pc, "wait-complete", retirement());
|
||||
if (reg < 0 || reg >= static_cast<int64_t>(target.synchronizationRegisterCount)
|
||||
|| count <= 0 || !waits.emplace(Key{core, reg}, Wait{end, count}).second) {
|
||||
error = "WAIT requires one positive exact count per register per generation";
|
||||
return false;
|
||||
}
|
||||
cores.at(core).work += retirement();
|
||||
cores.at(core).service[6] += retirement();
|
||||
opcodeService[static_cast<unsigned>(op)] += retirement();
|
||||
} else {
|
||||
if (peer < 0 || peer >= static_cast<int64_t>(target.processorCount)) {
|
||||
error = "direct transfer has an invalid peer";
|
||||
return false;
|
||||
}
|
||||
size_t complete = event(core, pc, op == Opcode::send ? "send-complete" : "receive-complete");
|
||||
edges.push_back({begin, complete, 0, 0});
|
||||
cores.at(core).tail = complete;
|
||||
if (op == Opcode::send) {
|
||||
auto request = network(core, pc, begin,
|
||||
target.getLinkServiceNs(target.controlMessageBytes, core, peer), 1);
|
||||
// SwitchSocket::send enqueues immediately in an unbounded FIFO.
|
||||
size_t enqueue = event(core, pc, "payload-enqueue");
|
||||
edges.push_back({enqueue, complete, retirement(), 0});
|
||||
auto payload = network(core, pc, enqueue, target.getLinkServiceNs(bytes, core, peer));
|
||||
sends[{core, peer}].push_back({enqueue, request.arrival, payload.arrival, bytes});
|
||||
} else {
|
||||
auto permission = network(core, pc, begin,
|
||||
target.getLinkServiceNs(target.controlMessageBytes, core, peer));
|
||||
receives[{peer, core}].push_back({complete, permission.arrival, permission.begin, bytes});
|
||||
}
|
||||
cores.at(core).work += local(bytes, op == Opcode::recv) + retirement();
|
||||
cores.at(core).service[2] += local(bytes, op == Opcode::recv) + retirement();
|
||||
opcodeService[static_cast<unsigned>(op)] += local(bytes, op == Opcode::recv) + retirement();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Analysis::readCore(int64_t core, llvm::StringRef data, const llvm::json::Array &groups) {
|
||||
if (data.size() < 12 || data.take_front(4) != "PIMB"
|
||||
|| llvm::support::endian::read32le(data.data() + 4) != 1) {
|
||||
error = "invalid binary instruction header"; return false;
|
||||
}
|
||||
uint32_t count = llvm::support::endian::read32le(data.data() + 8);
|
||||
if (data.size() != 12ull + 20ull * count) {
|
||||
error = "binary instruction count does not match file size"; return false;
|
||||
}
|
||||
if (!count) return true;
|
||||
size_t entry = event(core, 0, "body-entry");
|
||||
cores.emplace(core, Core{entry, entry, absent, absent});
|
||||
Core &state = cores.at(core);
|
||||
Cost inputBits = 0, outputBits = 0;
|
||||
for (uint32_t pc = 0; pc < count; ++pc) {
|
||||
const char *record = data.data() + 12 + 20ull * pc;
|
||||
unsigned rawOpcode = static_cast<uint8_t>(record[0]);
|
||||
if (rawOpcode > static_cast<unsigned>(Opcode::sync)) { error = "unsupported instruction opcode"; return false; }
|
||||
Opcode op = static_cast<Opcode>(rawOpcode);
|
||||
++opcodeCounts[rawOpcode];
|
||||
int32_t arg = llvm::support::endian::read32le(record + 4);
|
||||
int32_t a = llvm::support::endian::read32le(record + 8);
|
||||
int32_t b = llvm::support::endian::read32le(record + 12);
|
||||
int32_t length = llvm::support::endian::read32le(record + 16);
|
||||
++state.instructions;
|
||||
if (op <= Opcode::setbw) {
|
||||
if (op == Opcode::sld) { error = "scalar memory loads are unsupported by this diagnostic"; return false; }
|
||||
if (op == Opcode::setbw) {
|
||||
if (a <= 0 || b <= 0) { error = "invalid SETBW"; return false; }
|
||||
if (options.oraclePrecision && (a != 32 || b != 32)) {
|
||||
error = "oracle timing projection requires 32-bit native vector widths"; return false;
|
||||
}
|
||||
inputBits = options.oraclePrecision ? 8 : a;
|
||||
outputBits = options.oraclePrecision ? 8 : b;
|
||||
}
|
||||
// shortcut: serialize scalar issue; model frontend buffering before selection.
|
||||
Cost cost = issue ? target.processorPeriodNs : 0;
|
||||
state.pending += cost; state.service[5] += cost;
|
||||
opcodeService[static_cast<unsigned>(op)] += cost;
|
||||
continue;
|
||||
}
|
||||
if (length < 0 || op > Opcode::sync || op == Opcode::vsoftmax) {
|
||||
error = "unsupported instruction opcode or negative transfer length"; return false;
|
||||
}
|
||||
Cost bytes = length;
|
||||
if (options.oraclePrecision && (op == Opcode::ld || op == Opcode::st
|
||||
|| op == Opcode::lldi || op == Opcode::lmv || op == Opcode::send || op == Opcode::recv)) {
|
||||
if (length % 4) { error = "oracle timing projection requires element-aligned transfers"; return false; }
|
||||
bytes /= 4;
|
||||
}
|
||||
Cost in = (inputBits + 7) / 8, out = (outputBits + 7) / 8;
|
||||
if (op <= Opcode::vrsl && (!inputBits || !outputBits)) {
|
||||
error = "compute instruction precedes SETBW"; return false;
|
||||
}
|
||||
if (op >= Opcode::send) {
|
||||
if (!communication(core, pc, op, arg, a, b, bytes)) return false;
|
||||
continue;
|
||||
}
|
||||
if (op == Opcode::ld || op == Opcode::st) {
|
||||
bool write = op == Opcode::st;
|
||||
auto demand = target.getSharedMemoryDemand(bytes, 1, write);
|
||||
memory += demand;
|
||||
Cost completion = (write ? 0 : local(bytes, true)) + retirement();
|
||||
Cost cost = (write ? local(bytes, false) : 0) + demand.serviceNs + completion
|
||||
+ target.getSharedMemoryLinkServiceNs(write ? bytes : target.controlMessageBytes, core, false)
|
||||
+ target.getSharedMemoryLinkServiceNs(!write && target.sharedMemoryReadReturnsPayload ? bytes : 0, core, true);
|
||||
state.service[write ? 4 : 3] += cost;
|
||||
opcodeService[static_cast<unsigned>(op)] += cost;
|
||||
if (memoryQueue) {
|
||||
flush(core, pc);
|
||||
if (write) append(core, pc, "store-source-read", local(bytes, false));
|
||||
auto request = network(core, pc, state.tail,
|
||||
target.getSharedMemoryLinkServiceNs(write ? bytes : target.controlMessageBytes, core, false));
|
||||
size_t done = event(core, pc, "memory-service-complete");
|
||||
edges.push_back({request.arrival, done, demand.serviceNs, 0});
|
||||
memoryServices.emplace_back(done, demand.serviceNs);
|
||||
Cost reply = target.getSharedMemoryLinkServiceNs(
|
||||
!write && target.sharedMemoryReadReturnsPayload ? bytes : 0, core, true);
|
||||
size_t response = done;
|
||||
if (reply) {
|
||||
response = event(core, pc, "memory-response");
|
||||
edges.push_back({done, response, reply, 0});
|
||||
}
|
||||
state.lastNetwork = response;
|
||||
size_t complete = event(core, pc, "memory-complete");
|
||||
edges.push_back({response, complete, completion, 0});
|
||||
state.tail = complete;
|
||||
state.work += cost;
|
||||
continue;
|
||||
}
|
||||
if (!state.blockingNetworkInChunk) {
|
||||
flush(core, pc);
|
||||
if (write) {
|
||||
Cost read = local(bytes, false);
|
||||
append(core, pc, "store-source-read", read);
|
||||
state.work += read;
|
||||
cost -= read;
|
||||
}
|
||||
size_t begin = append(core, pc, "memory-queue-join");
|
||||
if (queues && state.lastNetwork != absent)
|
||||
edges.push_back({state.lastNetwork, begin, 0, 0});
|
||||
if (state.firstNetwork == absent)
|
||||
state.firstNetwork = begin;
|
||||
state.blockingNetworkInChunk = true;
|
||||
}
|
||||
// ROB=1 serializes these blocking requests. No external dependency joins
|
||||
// inside a chunk; retain their exact service sum without per-request nodes.
|
||||
state.pending += cost;
|
||||
continue;
|
||||
}
|
||||
Cost cost = 0;
|
||||
unsigned resource = 2;
|
||||
if (op == Opcode::mvmul) {
|
||||
if (arg <= 0 || length < 0 || static_cast<size_t>(length) >= groups.size()
|
||||
|| !groups[length].getAsInteger() || *groups[length].getAsInteger() <= 0) {
|
||||
error = "matrix instruction references an invalid array group"; return false;
|
||||
}
|
||||
Cost output = (target.matrixColumns * cellBits / arg) * *groups[length].getAsInteger() * out;
|
||||
cost = local(target.matrixRows * in * target.matrixInputReadMultiplier, false)
|
||||
+ target.getMatrixComputeLatencyNs(inputBits) + local(output, true);
|
||||
cost += retirement(true); resource = 0;
|
||||
} else if (op <= Opcode::vrsl) {
|
||||
bool binary = op >= Opcode::vvadd && op <= Opcode::vvsra;
|
||||
bool outputWidth = op == Opcode::vvmul || op == Opcode::vvsll || op == Opcode::vvsra || op == Opcode::vtanh || op == Opcode::vsigm || op == Opcode::vrsu || op == Opcode::vrsl;
|
||||
// The oracle's VectorUnit uses input width for VAVG/VVDMUL writeback.
|
||||
// It waits vector_latency_cycle nanoseconds, independently of core period.
|
||||
cost = local(bytes * in, false) * (binary ? 2 : 1)
|
||||
+ ((bytes + target.vectorWidth - 1) / target.vectorWidth) * target.vectorLatencyCycles
|
||||
+ local(bytes * (outputWidth ? out : in), true) + retirement();
|
||||
resource = 1;
|
||||
} else {
|
||||
cost = local(bytes, true) + (op == Opcode::lmv ? local(bytes, false) : 0) + retirement();
|
||||
}
|
||||
state.pending += cost;
|
||||
state.service[resource] += cost;
|
||||
opcodeService[static_cast<unsigned>(op)] += cost;
|
||||
}
|
||||
flush(core, count);
|
||||
edges.push_back({state.tail, state.entry, 0, 1});
|
||||
if (queues && state.firstNetwork != absent)
|
||||
edges.push_back({state.lastNetwork, state.firstNetwork, 0, 1});
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Analysis::connect() {
|
||||
if (sends.size() != receives.size() || signals.size() != waits.size()) {
|
||||
error = "communication endpoint sets differ"; return false;
|
||||
}
|
||||
for (const auto &[key, producers] : sends) {
|
||||
auto found = receives.find(key);
|
||||
if (found == receives.end() || found->second.size() != producers.size()) {
|
||||
error = "direct SEND/RECV FIFO counts differ"; return false;
|
||||
}
|
||||
for (auto [send, receive] : llvm::zip(producers, found->second)) {
|
||||
if (send.bytes != receive.bytes) { error = "direct payload sizes differ"; return false; }
|
||||
// The receiver responds after both its RECV and the sender request arrive.
|
||||
// Its outgoing FIFO may still contain earlier SYNC or transport requests.
|
||||
edges.push_back({send.requestArrival, receive.permissionDispatch, 0, 0});
|
||||
edges.push_back({receive.permissionArrival, send.enqueue, local(send.bytes, false), 0});
|
||||
edges.push_back({send.payloadArrival, receive.complete, local(send.bytes, true) + retirement(), 0});
|
||||
}
|
||||
}
|
||||
for (const auto &[key, pending] : waits) {
|
||||
auto found = signals.find(key);
|
||||
if (found == signals.end() || found->second.size() != static_cast<size_t>(pending.expected)) {
|
||||
error = "event register does not receive its exact static count"; return false;
|
||||
}
|
||||
for (const auto ¬ice : found->second)
|
||||
edges.push_back({notice.arrival, pending.end, retirement(), 0});
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
llvm::json::Object Analysis::report() {
|
||||
llvm::json::Object result;
|
||||
if (cores.empty()) {
|
||||
error = "artifact has no active repeating instruction stream";
|
||||
result["status"] = "unavailable"; result["reason"] = error; return result;
|
||||
}
|
||||
if (!connect()) { result["status"] = "unavailable"; result["reason"] = error; return result; }
|
||||
result["global_memory_service_ns"] = static_cast<int64_t>(memory.serviceNs);
|
||||
result["global_read_bytes"] = static_cast<int64_t>(memory.readBytes);
|
||||
result["global_write_bytes"] = static_cast<int64_t>(memory.writeBytes);
|
||||
result["global_read_requests"] = static_cast<int64_t>(memory.readRequests);
|
||||
result["global_write_requests"] = static_cast<int64_t>(memory.writeRequests);
|
||||
if (!options.detailed) {
|
||||
result["status"] = "estimated";
|
||||
result["memory_controller"] = queueReport();
|
||||
return result;
|
||||
}
|
||||
auto estimate = analyzePeriodicDependencies(events.size(), edges, error);
|
||||
if (mlir::failed(estimate)) { result["status"] = "unavailable"; result["reason"] = error; return result; }
|
||||
result["status"] = "estimated";
|
||||
result["recurrence_lower_ns"] = estimate->recurrenceLowerNs;
|
||||
result["recurrence_upper_ns"] = estimate->recurrenceUpperNs;
|
||||
result["within_generation_span_ns"] = static_cast<int64_t>(estimate->withinGenerationSpanNs);
|
||||
result["interval_estimate_ns"] = std::max(estimate->recurrenceUpperNs, static_cast<double>(memory.serviceNs));
|
||||
result["limiting_bound"] = memory.serviceNs > estimate->recurrenceUpperNs ? "global-memory" : "recurrence";
|
||||
result["events"] = static_cast<int64_t>(events.size());
|
||||
result["edges"] = static_cast<int64_t>(edges.size());
|
||||
// Keep small timing fixtures inspectable without dumping network-size graphs.
|
||||
if (events.size() <= 128) {
|
||||
llvm::json::Array nodes, dependencies;
|
||||
for (const auto &node : events)
|
||||
nodes.push_back(llvm::json::Object{{"core", node.core}, {"pc", node.pc}, {"kind", node.kind}});
|
||||
for (const auto &edge : edges)
|
||||
dependencies.push_back(llvm::json::Object{{"source", static_cast<int64_t>(edge.source)},
|
||||
{"target", static_cast<int64_t>(edge.target)}, {"delay_ns", static_cast<int64_t>(edge.delayNs)},
|
||||
{"distance", edge.distance}});
|
||||
result["timing_graph"] = llvm::json::Object{{"events", std::move(nodes)}, {"dependencies", std::move(dependencies)}};
|
||||
}
|
||||
result["network_queues"] = queues; result["instruction_issue"] = issue;
|
||||
if (memoryQueue) result["memory_controller"] = queueReport();
|
||||
result["resource_service_columns"] = llvm::json::Array{"matrix", "vector", "local_transfer",
|
||||
"global_load", "global_store", "scalar_issue", "synchronization"};
|
||||
Cost directBytes = 0, directRequests = 0;
|
||||
for (const auto &[key, transfers] : sends)
|
||||
for (const auto &transfer : transfers) { directBytes += transfer.bytes; ++directRequests; }
|
||||
result["direct_requests"] = static_cast<int64_t>(directRequests);
|
||||
result["direct_bytes"] = static_cast<int64_t>(directBytes);
|
||||
llvm::json::Object opcodeDemand, instructionCounts;
|
||||
for (size_t op = 0; op < opcodeCounts.size(); ++op)
|
||||
if (opcodeCounts[op]) {
|
||||
opcodeDemand[pim_binary::kOpcodeNames[op]] = static_cast<int64_t>(opcodeService[static_cast<unsigned>(op)]);
|
||||
instructionCounts[pim_binary::kOpcodeNames[op]] = static_cast<int64_t>(opcodeCounts[op]);
|
||||
}
|
||||
result["opcode_service_ns"] = std::move(opcodeDemand);
|
||||
result["instruction_counts"] = std::move(instructionCounts);
|
||||
llvm::json::Array perCore, cycle;
|
||||
Cost maximumCoreWork = 0;
|
||||
for (const auto &[core, state] : cores) {
|
||||
maximumCoreWork = std::max(maximumCoreWork, state.work);
|
||||
llvm::json::Array resource;
|
||||
for (Cost value : state.service) resource.push_back(static_cast<int64_t>(value));
|
||||
perCore.push_back(llvm::json::Object{{"core", core}, {"instructions", static_cast<int64_t>(state.instructions)},
|
||||
{"serial_work_ns", static_cast<int64_t>(state.work)}, {"resource_service_ns", std::move(resource)}});
|
||||
}
|
||||
std::map<int64_t, Cost> cycleCores;
|
||||
Cost cycleDelay = 0, cycleDistance = 0;
|
||||
for (size_t index : estimate->criticalCycle) {
|
||||
const auto &edge = edges[index];
|
||||
const auto &from = events[edge.source], &to = events[edge.target];
|
||||
cycleCores[to.core] += edge.delayNs;
|
||||
cycleDelay += edge.delayNs; cycleDistance += edge.distance;
|
||||
if (cycle.size() < 128)
|
||||
cycle.push_back(llvm::json::Object{{"source_core", from.core}, {"target_core", to.core},
|
||||
{"source_pc", from.pc}, {"target_pc", to.pc}, {"kind", to.kind},
|
||||
{"delay_ns", static_cast<int64_t>(edge.delayNs)}, {"distance", edge.distance}});
|
||||
}
|
||||
llvm::json::Array critical;
|
||||
for (auto [core, delay] : cycleCores)
|
||||
critical.push_back(llvm::json::Object{{"core", core}, {"delay_ns", static_cast<int64_t>(delay)}});
|
||||
result["critical_cycle"] = std::move(cycle); result["critical_cores"] = std::move(critical);
|
||||
result["critical_cycle_edges"] = static_cast<int64_t>(estimate->criticalCycle.size());
|
||||
result["critical_cycle_delay_ns"] = static_cast<int64_t>(cycleDelay);
|
||||
result["critical_cycle_distance"] = static_cast<int64_t>(cycleDistance);
|
||||
result["per_core"] = std::move(perCore);
|
||||
result["maximum_core_serial_work_ns"] = static_cast<int64_t>(maximumCoreWork);
|
||||
result["omitted_effects"] = llvm::json::Array{"global-memory arbitration", "clock-phase rounding and frontend buffering",
|
||||
"scalar issue overlap (charged serially)", "initial inference bootstrap"};
|
||||
return result;
|
||||
}
|
||||
|
||||
llvm::json::Object Analysis::queueReport() {
|
||||
auto queued = estimateQueuedPeriod(events, edges, memoryServices, cores, false);
|
||||
auto alternative = estimateQueuedPeriod(events, edges, memoryServices, cores, true);
|
||||
queued["alternative_tie_status"] = alternative.getString("status").value();
|
||||
if (auto reason = alternative.getString("reason"))
|
||||
queued["alternative_tie_reason"] = reason->str();
|
||||
if (auto interval = alternative.getNumber("interval_ns"))
|
||||
queued["alternative_tie_interval_ns"] = *interval;
|
||||
if (auto interval = queued.getNumber("interval_ns"))
|
||||
queued["memory_service_fraction"] = memory.serviceNs / *interval;
|
||||
queued["arbitration"] = "FIFO by predicted controller arrival";
|
||||
return queued;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
llvm::json::Object onnx_mlir::analyzePimInstructions(const PimInstructionProgram &program,
|
||||
const PimInstructionTiming &target, int64_t cellBits, PimPeriodicOptions options) {
|
||||
Analysis analysis;
|
||||
analysis.target = target;
|
||||
analysis.cellBits = cellBits;
|
||||
analysis.options = options;
|
||||
analysis.queues = options.networkQueues;
|
||||
analysis.issue = options.instructionIssue;
|
||||
analysis.memoryQueue = options.memoryController;
|
||||
auto unavailable = [](llvm::StringRef reason) {
|
||||
return llvm::json::Object{{"status", "unavailable"}, {"reason", reason.str()}};
|
||||
};
|
||||
if (!target.hasPeriodicTransferTiming() || cellBits <= 0)
|
||||
return unavailable("target has no supported instruction timing contract");
|
||||
if (program.instructions.empty() || program.instructions.size() > target.processorCount
|
||||
|| program.instructions.size() != program.arrayGroups.size())
|
||||
return unavailable("instruction program core count or array groups do not fit the target");
|
||||
for (size_t id = 0; id < program.instructions.size(); ++id) {
|
||||
llvm::json::Array groups;
|
||||
for (int64_t count : program.arrayGroups[id]) groups.push_back(count);
|
||||
if (!analysis.readCore(id, program.instructions[id], groups))
|
||||
return unavailable(analysis.error);
|
||||
}
|
||||
return analysis.report();
|
||||
}
|
||||
|
||||
void onnx_mlir::configurePimScheduleCosts(spatial::SchedulingTarget &target,
|
||||
PimInstructionTiming timing) {
|
||||
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);
|
||||
};
|
||||
auto contract = getPimPeriodicTimingContract();
|
||||
if (!contract) target.wholeScheduleCostUnavailable = llvm::toString(contract.takeError());
|
||||
if (!hardware->hasPeriodicTransferTiming())
|
||||
target.wholeScheduleCostUnavailable = "target has no supported instruction timing contract";
|
||||
if (pimDisableSynchronization)
|
||||
target.wholeScheduleCostUnavailable = "synchronization ablation has no periodic queue timing contract";
|
||||
if (!target.wholeScheduleCostUnavailable.empty()) return;
|
||||
target.prepareScheduleCost = [hardware, cellBits = *contract](mlir::ModuleOp module,
|
||||
llvm::json::Object &summary) -> mlir::FailureOr<spatial::ScheduleCostQuery> {
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
PimInstructionProgram program;
|
||||
PimCodegenTiming timing;
|
||||
std::string unused;
|
||||
if (compileToPimCode(module, unused, &program, &timing) != CompilerSuccess)
|
||||
return mlir::failure();
|
||||
summary["codegen_preparation_seconds"] = timing.preparationSeconds;
|
||||
summary["codegen_emission_seconds"] = timing.emissionSeconds;
|
||||
summary["instruction_generation_seconds"] = std::chrono::duration<double>(
|
||||
std::chrono::steady_clock::now() - start).count();
|
||||
llvm::SHA256 hash;
|
||||
int64_t instructionBytes = 0;
|
||||
for (size_t core = 0; core < program.instructions.size(); ++core) {
|
||||
instructionBytes += program.instructions[core].size();
|
||||
hash.update(program.instructions[core]);
|
||||
for (int64_t group : program.arrayGroups[core]) hash.update(std::to_string(group) + ",");
|
||||
hash.update(";");
|
||||
}
|
||||
summary["instruction_bytes"] = instructionBytes;
|
||||
summary["instruction_count"] = (instructionBytes
|
||||
- pim_binary::kHeaderSize * program.instructions.size()) / pim_binary::kRecordSize;
|
||||
spatial::ScheduleCostQuery query;
|
||||
query.identity = llvm::toHex(hash.final());
|
||||
query.evaluate = [program = std::move(program), hardware, cellBits](llvm::json::Object &summary) {
|
||||
PimPeriodicOptions options;
|
||||
options.oraclePrecision = true;
|
||||
auto report = analyzePimInstructions(program, *hardware, cellBits, options);
|
||||
for (const char *field : {"global_memory_service_ns", "global_read_bytes", "global_write_bytes",
|
||||
"global_read_requests", "global_write_requests"})
|
||||
if (auto value = report.getInteger(field)) summary[field] = *value;
|
||||
spatial::WholeScheduleCost cost;
|
||||
// Conservative selection margin; not a timing correction or formal bound.
|
||||
cost.relativeUncertainty = 0.021;
|
||||
if (auto *queue = report.getObject("memory_controller")) {
|
||||
if (queue->getString("status") == "estimated"
|
||||
&& queue->getString("alternative_tie_status") == "estimated") {
|
||||
cost.primary = queue->getNumber("interval_ns");
|
||||
cost.alternative = queue->getNumber("alternative_tie_interval_ns");
|
||||
}
|
||||
if (auto reason = queue->getString("reason")) cost.reason = reason->str();
|
||||
if (!cost.eligible() && cost.reason.empty())
|
||||
if (auto reason = queue->getString("alternative_tie_reason"))
|
||||
cost.reason = "alternative arbitration: " + reason->str();
|
||||
} else if (auto reason = report.getString("reason")) cost.reason = reason->str();
|
||||
if (!cost.eligible() && cost.reason.empty())
|
||||
cost.reason = "arbitration sensitivity estimate unavailable or nonconverged";
|
||||
return cost;
|
||||
};
|
||||
return query;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
|
||||
#include "llvm/Support/JSON.h"
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace onnx_mlir {
|
||||
namespace spatial { struct SchedulingTarget; }
|
||||
struct PimInstructionTiming;
|
||||
void configurePimScheduleCosts(spatial::SchedulingTarget &target, PimInstructionTiming timing);
|
||||
|
||||
// Binary instructions, indexed by physical core. No executable or measured data.
|
||||
struct PimInstructionProgram {
|
||||
std::vector<std::string> instructions;
|
||||
std::vector<std::vector<int64_t>> arrayGroups;
|
||||
};
|
||||
|
||||
struct PimPeriodicOptions {
|
||||
bool networkQueues = true;
|
||||
bool instructionIssue = true;
|
||||
bool memoryController = true;
|
||||
bool detailed = false;
|
||||
// Apply the oracle's fp32-to-int8 timing projection without changing the program.
|
||||
bool oraclePrecision = false;
|
||||
};
|
||||
|
||||
llvm::json::Object analyzePimInstructions(const PimInstructionProgram &program,
|
||||
const PimInstructionTiming &target, int64_t cellBits,
|
||||
PimPeriodicOptions options = {});
|
||||
} // namespace onnx_mlir
|
||||
@@ -0,0 +1,76 @@
|
||||
#include "PimPeriodicAnalysis.hpp"
|
||||
#include "PimInstructionTiming.hpp"
|
||||
#include "PimCompilerOptions.hpp"
|
||||
#include "PimCompilerUtils.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/SchedulingTarget.hpp"
|
||||
#include "llvm/Support/CommandLine.h"
|
||||
#include "llvm/Support/FormatVariadic.h"
|
||||
#include "llvm/Support/MemoryBuffer.h"
|
||||
#include <chrono>
|
||||
|
||||
using namespace onnx_mlir;
|
||||
namespace {
|
||||
llvm::cl::opt<std::string> artifact(llvm::cl::Positional, llvm::cl::Required,
|
||||
llvm::cl::desc("PIM binary artifact directory (native or oracle-exported)"));
|
||||
llvm::cl::opt<bool> queues("model-network-queues", llvm::cl::init(true));
|
||||
llvm::cl::opt<bool> issue("model-issue", llvm::cl::init(true));
|
||||
llvm::cl::opt<bool> oraclePrecision("oracle-precision", llvm::cl::init(false),
|
||||
llvm::cl::desc("Project native fp32 instructions to oracle int8 timing"));
|
||||
llvm::cl::opt<bool> memoryQueue("model-memory-controller", llvm::cl::init(false));
|
||||
llvm::Expected<llvm::json::Object> readJson(llvm::StringRef path) {
|
||||
auto buffer = llvm::MemoryBuffer::getFile(path);
|
||||
if (!buffer) return llvm::errorCodeToError(buffer.getError());
|
||||
auto parsed = llvm::json::parse(buffer.get()->getBuffer());
|
||||
if (!parsed) return parsed.takeError();
|
||||
if (!parsed->getAsObject()) return llvm::createStringError("expected a JSON object");
|
||||
return std::move(*parsed->getAsObject());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
llvm::cl::ParseCommandLineOptions(argc, argv, "Post-codegen periodic PIM diagnostics\n");
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
auto program = readJson(artifact + "/config.json");
|
||||
auto cellBits = getPimPeriodicTimingContract();
|
||||
if (!program || !cellBits) {
|
||||
llvm::errs() << (!program ? llvm::toString(program.takeError()) : llvm::toString(cellBits.takeError())) << '\n';
|
||||
return 1;
|
||||
}
|
||||
auto target = getPimInstructionTiming();
|
||||
PimInstructionProgram instructions;
|
||||
auto *groups = program->getObject("array_group_map");
|
||||
if (!groups) { llvm::errs() << "missing physical array groups\n"; return 1; }
|
||||
auto coreCount = program->getInteger("core_cnt");
|
||||
if (!coreCount || *coreCount <= 0 || *coreCount > static_cast<int64_t>(target.processorCount)) {
|
||||
llvm::errs() << "artifact core count does not fit the target\n"; return 1;
|
||||
}
|
||||
for (int64_t id = 0; id < *coreCount; ++id) {
|
||||
auto path = artifact + "/core_" + std::to_string(id) + ".pim";
|
||||
auto *array = groups->getArray("core" + std::to_string(id));
|
||||
if (!array) { llvm::errs() << "missing physical core array groups\n"; return 1; }
|
||||
auto buffer = llvm::MemoryBuffer::getFile(path);
|
||||
if (!buffer) { llvm::errs() << "cannot read instruction artifact\n"; return 1; }
|
||||
instructions.instructions.push_back(buffer.get()->getBuffer().str());
|
||||
std::vector<int64_t> counts;
|
||||
for (const auto &value : *array) {
|
||||
auto count = value.getAsInteger();
|
||||
if (!count) { llvm::errs() << "invalid array group\n"; return 1; }
|
||||
counts.push_back(*count);
|
||||
}
|
||||
instructions.arrayGroups.push_back(std::move(counts));
|
||||
}
|
||||
PimPeriodicOptions options;
|
||||
options.detailed = true;
|
||||
options.oraclePrecision = oraclePrecision;
|
||||
options.networkQueues = queues;
|
||||
options.instructionIssue = issue;
|
||||
options.memoryController = memoryQueue;
|
||||
auto report = analyzePimInstructions(instructions, target, *cellBits, options);
|
||||
report["diagnostic_only"] = true;
|
||||
report["selection_eligible"] = false;
|
||||
bool available = report.getString("status") == "estimated";
|
||||
report["analysis_wall_ms"] = std::chrono::duration<double, std::milli>(
|
||||
std::chrono::steady_clock::now() - start).count();
|
||||
llvm::outs() << llvm::formatv("{0:2}\n", llvm::json::Value(std::move(report)));
|
||||
return available ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
#include "PimPipelineSelection.hpp"
|
||||
#include "PimCompilerOptions.hpp"
|
||||
#include "PimCompilerUtils.hpp"
|
||||
#include "src/Accelerators/PIM/Common/Support/DebugDump.hpp"
|
||||
#include "src/Accelerators/PIM/Common/Support/FileSystemUtils.hpp"
|
||||
#include "src/Accelerators/PIM/Common/Support/ReportUtils.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/ScheduledSpatialPasses.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/SpatialTargetResources.hpp"
|
||||
#include "mlir/Pass/PassManager.h"
|
||||
#include "mlir/Pass/PassInstrumentation.h"
|
||||
#include "src/Compiler/CompilerOptions.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/ScheduleEvaluation.hpp"
|
||||
#include "llvm/Support/FormatVariadic.h"
|
||||
#include "llvm/Support/JSON.h"
|
||||
#include "llvm/Support/raw_os_ostream.h"
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
|
||||
using namespace mlir;
|
||||
using namespace onnx_mlir;
|
||||
using namespace onnx_mlir::spatial;
|
||||
|
||||
namespace {
|
||||
using Clock = std::chrono::steady_clock;
|
||||
double elapsed(Clock::time_point start) {
|
||||
return std::chrono::duration<double>(Clock::now() - start).count();
|
||||
}
|
||||
|
||||
llvm::json::Object countIR(Operation *root) {
|
||||
int64_t operations = 0, values = 0;
|
||||
root->walk([&](Operation *op) {
|
||||
++operations;
|
||||
values += op->getNumResults();
|
||||
for (Region ®ion : op->getRegions())
|
||||
for (Block &block : region) values += block.getNumArguments();
|
||||
});
|
||||
return llvm::json::Object{{"operations", operations}, {"values", values}};
|
||||
}
|
||||
|
||||
// Enabled with the existing compiler timing option. No instruction expansion.
|
||||
struct CandidateTiming final : PassInstrumentation {
|
||||
llvm::json::Object &summary;
|
||||
Clock::time_point start;
|
||||
explicit CandidateTiming(llvm::json::Object &summary) : summary(summary) {}
|
||||
void runBeforePass(Pass *pass, Operation *op) override {
|
||||
if (pass->getArgument() == "pim-one-shot-bufferization")
|
||||
summary["bufferization_input_ir"] = countIR(op);
|
||||
start = Clock::now();
|
||||
}
|
||||
void runAfterPass(Pass *pass, Operation *) override {
|
||||
auto *phases = summary.getObject("lowering_phases_seconds");
|
||||
if (!phases) {
|
||||
summary["lowering_phases_seconds"] = llvm::json::Object{};
|
||||
phases = summary.getObject("lowering_phases_seconds");
|
||||
}
|
||||
(*phases)[pass->getName()] = elapsed(start);
|
||||
}
|
||||
};
|
||||
|
||||
struct PimPipelineSelectionPass final : PassWrapper<PimPipelineSelectionPass, OperationPass<ModuleOp>> {
|
||||
MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(PimPipelineSelectionPass)
|
||||
PimPipelineSelectionPass(const SchedulingTarget &target, const SpatialTargetResources &resources,
|
||||
size_t stages, SpatialDataflowExportStage exportStage)
|
||||
: target(target), resources(resources), stages(stages), exportStage(exportStage) {}
|
||||
SchedulingTarget target;
|
||||
SpatialTargetResources resources;
|
||||
size_t stages;
|
||||
SpatialDataflowExportStage exportStage;
|
||||
|
||||
StringRef getArgument() const override { return "pim-pipeline-selection"; }
|
||||
StringRef getDescription() const override { return "Select a throughput pipeline using static instruction queue analysis"; }
|
||||
|
||||
LogicalResult lower(ModuleOp module, llvm::json::Object *summary = nullptr) {
|
||||
PassManager pm(module.getContext());
|
||||
addPimLoweringPasses(pm, resources, EmitPimCodegen, /*reportProgress=*/false);
|
||||
if (enableTiming && summary)
|
||||
pm.addInstrumentation(std::make_unique<CandidateTiming>(*summary));
|
||||
return pm.run(module);
|
||||
}
|
||||
|
||||
LogicalResult evaluate(ModuleOp checkpoint, const MergeScheduleResult &schedule,
|
||||
OwningOpRef<ModuleOp> &candidate,
|
||||
std::string &scheduleReport, llvm::json::Object &summary) {
|
||||
auto begin = Clock::now();
|
||||
IRMapping mapping;
|
||||
candidate = cast<ModuleOp>(checkpoint->clone(mapping));
|
||||
auto remapped = remapSpatialSchedule(schedule, mapping);
|
||||
if (failed(realizeSpatialSchedule(*candidate, remapped, target, stages,
|
||||
SpatialDataflowExportStage::None, nullptr, &scheduleReport))
|
||||
|| failed(lower(*candidate, &summary))) return failure();
|
||||
if (enableTiming) summary["codegen_input_ir"] = countIR(candidate->getOperation());
|
||||
summary["lowering_seconds"] = elapsed(begin);
|
||||
return success();
|
||||
}
|
||||
|
||||
void runOnOperation() override {
|
||||
ModuleOp module = getOperation();
|
||||
auto start = Clock::now();
|
||||
std::string unsupported;
|
||||
if (!target.prepareScheduleCost)
|
||||
unsupported = target.wholeScheduleCostUnavailable.empty()
|
||||
? "target has no whole-schedule cost query" : target.wholeScheduleCostUnavailable;
|
||||
auto prepared = prepareSpatialSchedules(module, target, stages, unsupported.empty());
|
||||
if (failed(prepared)) { signalPassFailure(); return; }
|
||||
bool singleCandidate = unsupported.empty() && prepared->candidates.size() == 1;
|
||||
double generationSeconds = elapsed(start);
|
||||
std::vector<WholeScheduleCost> scores(prepared->candidates.size());
|
||||
llvm::json::Array summaries;
|
||||
OwningOpRef<ModuleOp> bestModule;
|
||||
std::string bestScheduleReport;
|
||||
size_t bestIndex = 0;
|
||||
double loweringSeconds = 0, instructionSeconds = 0, queueSeconds = 0;
|
||||
size_t lowered = 0, analyzed = 0, unavailable = 0, duplicates = 0;
|
||||
for (size_t i = 0; i < prepared->candidates.size(); ++i) {
|
||||
llvm::json::Object summary{{"index", static_cast<int64_t>(i)}};
|
||||
if (!unsupported.empty()) {
|
||||
scores[i].reason = unsupported;
|
||||
} else if (singleCandidate) {
|
||||
scores[i].reason = "one distinct generated schedule; no cost comparison required";
|
||||
} else {
|
||||
ScopedCompilerOutputSuppression silence;
|
||||
OwningOpRef<ModuleOp> candidate;
|
||||
std::string scheduleReport;
|
||||
if (failed(evaluate(module, prepared->candidates[i], candidate, scheduleReport, summary))) {
|
||||
if (!i) { signalPassFailure(); return; }
|
||||
scores[i].reason = "candidate lowering failed verification";
|
||||
} else {
|
||||
++lowered;
|
||||
loweringSeconds += *summary.getNumber("lowering_seconds");
|
||||
auto query = target.prepareScheduleCost(*candidate, summary);
|
||||
if (failed(query)) {
|
||||
if (!i) { signalPassFailure(); return; }
|
||||
scores[i].reason = "candidate cost preparation failed verification";
|
||||
++unavailable;
|
||||
summary["eligible"] = false;
|
||||
summary["reason"] = scores[i].reason;
|
||||
summaries.push_back(std::move(summary));
|
||||
continue;
|
||||
}
|
||||
instructionSeconds += summary.getNumber("instruction_generation_seconds").value_or(0);
|
||||
scores[i].identity = query->identity;
|
||||
auto duplicate = std::find_if(scores.begin(), scores.begin() + i,
|
||||
[&](const WholeScheduleCost &other) { return other.identity == scores[i].identity; });
|
||||
if (duplicate != scores.begin() + i) {
|
||||
++duplicates;
|
||||
scores[i].reason = "duplicate emitted instruction program";
|
||||
summary["duplicate_of"] = static_cast<int64_t>(duplicate - scores.begin());
|
||||
} else {
|
||||
auto begin = Clock::now();
|
||||
scores[i] = query->evaluate(summary);
|
||||
scores[i].identity = query->identity;
|
||||
double seconds = elapsed(begin);
|
||||
queueSeconds += seconds;
|
||||
++analyzed;
|
||||
summary["queue_seconds"] = seconds;
|
||||
}
|
||||
std::string partialReason;
|
||||
size_t partialSelection = selectPipelineCandidate(
|
||||
llvm::ArrayRef<WholeScheduleCost>(scores.data(), i + 1), partialReason);
|
||||
if (!bestModule || partialSelection == i) {
|
||||
bestIndex = i;
|
||||
bestModule = std::move(candidate);
|
||||
bestScheduleReport = std::move(scheduleReport);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!singleCandidate && !scores[i].eligible()
|
||||
&& scores[i].reason != "duplicate emitted instruction program") ++unavailable;
|
||||
summary["eligible"] = scores[i].eligible();
|
||||
summary["identity"] = scores[i].identity;
|
||||
if (scores[i].primary) summary["interval_ns"] = *scores[i].primary;
|
||||
if (scores[i].alternative) summary["alternative_tie_interval_ns"] = *scores[i].alternative;
|
||||
if (scores[i].relativeUncertainty)
|
||||
summary["relative_prediction_uncertainty"] = *scores[i].relativeUncertainty;
|
||||
if (!scores[i].reason.empty()) summary["reason"] = scores[i].reason;
|
||||
summaries.push_back(std::move(summary));
|
||||
}
|
||||
std::string reason;
|
||||
size_t selected = selectPipelineCandidate(scores, reason);
|
||||
if (singleCandidate) reason = scores.front().reason;
|
||||
else if (!unsupported.empty()) reason += ": " + unsupported;
|
||||
else if (!scores.front().eligible() && !scores.front().reason.empty())
|
||||
reason += ": " + scores.front().reason;
|
||||
auto finalizeStart = Clock::now();
|
||||
bool spatialArtifacts = exportStage != SpatialDataflowExportStage::None
|
||||
|| pimPeriodicDiagnostics || isPimIrDumpEnabled();
|
||||
// Explicit Spatial diagnostics require the pre-lowering representation.
|
||||
if (!bestModule || spatialArtifacts) {
|
||||
if (failed(realizeSpatialSchedule(module, prepared->candidates[selected], target,
|
||||
stages, exportStage, pimPeriodicDiagnostics ? &prepared->graph : nullptr))) { signalPassFailure(); return; }
|
||||
} else {
|
||||
auto file = openDialectDumpFileWithExtension("spatial3_scheduled_no_comm", "/reports", "txt");
|
||||
if (file) file << bestScheduleReport;
|
||||
}
|
||||
if (bestModule) {
|
||||
assert(selected == bestIndex && "retained module must be the selected candidate");
|
||||
module->setAttrs((*bestModule)->getAttrs());
|
||||
module.getBodyRegion().takeBody(bestModule->getBodyRegion());
|
||||
} else if (failed(lower(module))) { signalPassFailure(); return; }
|
||||
llvm::errs() << "Queue-aware pipeline: candidate " << selected << " of " << scores.size()
|
||||
<< "; " << reason << "\n";
|
||||
llvm::json::Object report{{"selection", static_cast<int64_t>(selected)}, {"reason", reason},
|
||||
{"static_analysis", true}, {"strategy", "queue-aware"}, {"candidates", std::move(summaries)},
|
||||
{"single_candidate_analysis_skipped", singleCandidate},
|
||||
{"candidate_generation_seconds", generationSeconds}, {"candidate_lowering_seconds", loweringSeconds},
|
||||
{"instruction_generation_seconds", instructionSeconds},
|
||||
{"queue_seconds", queueSeconds}, {"finalization_seconds", elapsed(finalizeStart)}, {"total_seconds", elapsed(start)},
|
||||
{"generated_candidates", static_cast<int64_t>(scores.size())},
|
||||
{"lowered_candidates", static_cast<int64_t>(lowered)},
|
||||
{"reused_lowered_candidate", static_cast<bool>(bestModule)},
|
||||
{"reconstructed_spatial_artifacts", spatialArtifacts && static_cast<bool>(bestModule)},
|
||||
{"analyzed_candidates", static_cast<int64_t>(analyzed)},
|
||||
{"unavailable_estimates", static_cast<int64_t>(unavailable)},
|
||||
{"duplicate_programs", static_cast<int64_t>(duplicates)}, {"temporary_disk_bytes", 0}};
|
||||
auto file = openReportFileWithExtension("pipeline_selection", "json");
|
||||
if (file) { llvm::raw_os_ostream out(file); out << llvm::formatv("{0:2}\n", llvm::json::Value(std::move(report))); }
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
std::unique_ptr<Pass> onnx_mlir::createPimPipelineSelectionPass(
|
||||
const SchedulingTarget &target, const SpatialTargetResources &resources,
|
||||
size_t stages, SpatialDataflowExportStage exportStage) {
|
||||
return std::make_unique<PimPipelineSelectionPass>(target, resources, stages, exportStage);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
#include "mlir/Pass/Pass.h"
|
||||
|
||||
namespace onnx_mlir {
|
||||
namespace spatial { struct SchedulingTarget; struct SpatialTargetResources; enum class SpatialDataflowExportStage; }
|
||||
std::unique_ptr<mlir::Pass> createPimPipelineSelectionPass(
|
||||
const spatial::SchedulingTarget &target, const spatial::SpatialTargetResources &resources,
|
||||
size_t stages, spatial::SpatialDataflowExportStage exportStage);
|
||||
} // namespace onnx_mlir
|
||||
@@ -0,0 +1,467 @@
|
||||
#include "PimScheduleDiagnostic.hpp"
|
||||
#include "PimInstructionTiming.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/DeferredTransferPlanning.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/PeriodicDependencies.hpp"
|
||||
#include "src/Accelerators/PIM/Common/Support/DebugDump.hpp"
|
||||
|
||||
#include "llvm/ADT/MapVector.h"
|
||||
#include "llvm/Support/JSON.h"
|
||||
#include "llvm/Support/raw_os_ostream.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <map>
|
||||
|
||||
namespace onnx_mlir {
|
||||
using namespace spatial;
|
||||
namespace {
|
||||
|
||||
struct Event {
|
||||
int64_t core;
|
||||
llvm::StringRef kind;
|
||||
int64_t identity;
|
||||
};
|
||||
struct DirectEndpoint {
|
||||
size_t begin;
|
||||
size_t end;
|
||||
int64_t core;
|
||||
Cost bytes;
|
||||
};
|
||||
struct Signal {
|
||||
size_t event;
|
||||
int64_t core;
|
||||
};
|
||||
struct Wait {
|
||||
size_t event;
|
||||
int64_t count;
|
||||
};
|
||||
using Register = std::pair<int64_t, unsigned>;
|
||||
|
||||
class PeriodicPlan {
|
||||
public:
|
||||
PeriodicPlan(const PimInstructionTiming &target,
|
||||
const DeferredTransferPlan &transfers)
|
||||
: target(target), transfers(transfers), computeWork(target.processorCount),
|
||||
entry(target.processorCount), tail(target.processorCount),
|
||||
active(target.processorCount) {}
|
||||
|
||||
bool build(const ComputeGraph &graph,
|
||||
const ScheduledComputeMaterializationResult &materialization,
|
||||
const DeferredBoundaryPlan &boundaries);
|
||||
|
||||
const PimInstructionTiming ⌖
|
||||
const DeferredTransferPlan &transfers;
|
||||
std::vector<Event> events;
|
||||
std::vector<PeriodicDependency> edges;
|
||||
SharedMemoryDemand boundaryMemory;
|
||||
std::vector<Cost> computeWork;
|
||||
std::string error;
|
||||
void recordSynchronization(llvm::json::Object &report) const;
|
||||
|
||||
private:
|
||||
size_t event(int64_t core, llvm::StringRef kind, int64_t identity = -1) {
|
||||
events.push_back({core, kind, identity});
|
||||
return events.size() - 1;
|
||||
}
|
||||
size_t append(int64_t core, llvm::StringRef kind, Cost delay = 0,
|
||||
int64_t identity = -1) {
|
||||
size_t next = event(core, kind, identity);
|
||||
edges.push_back({tail[core], next, delay, 0});
|
||||
tail[core] = next;
|
||||
return next;
|
||||
}
|
||||
void signal(int64_t source, int64_t targetCore, unsigned reg,
|
||||
llvm::StringRef kind) {
|
||||
size_t begin = append(source, kind, 0, targetCore);
|
||||
signals[{targetCore, reg}].push_back({begin, source});
|
||||
append(source, "signal-complete", target.signalIssueNs);
|
||||
}
|
||||
void wait(int64_t core, unsigned reg, int64_t count, llvm::StringRef kind) {
|
||||
if (!count)
|
||||
return;
|
||||
size_t next = append(core, kind, 0, reg);
|
||||
if (!waits.try_emplace({core, reg}, Wait{next, count}).second)
|
||||
error = "multiple waits consume one event register in a generation";
|
||||
}
|
||||
void entrySynchronization();
|
||||
void completionSynchronization();
|
||||
bool boundary(const BoundaryProgram &program);
|
||||
bool transfer(const ScheduledTransferSlice &slice, bool send);
|
||||
bool connect();
|
||||
|
||||
std::vector<size_t> entry, tail;
|
||||
std::vector<bool> active;
|
||||
std::map<Register, std::vector<Signal>> signals;
|
||||
std::map<Register, Wait> waits;
|
||||
llvm::MapVector<int64_t, DirectEndpoint> sends, receives;
|
||||
};
|
||||
|
||||
void PeriodicPlan::entrySynchronization() {
|
||||
for (const ScheduledInfo &scheduled : transfers.scheduled)
|
||||
for (int64_t core : scheduled.cores) {
|
||||
auto found = transfers.hostReleaseSignals.find(core);
|
||||
if (found != transfers.hostReleaseSignals.end())
|
||||
for (HostReleaseSignal release : found->second)
|
||||
signal(core, release.writerCore, release.eventRegister, "free-signal");
|
||||
}
|
||||
unsigned rounds = 0;
|
||||
for (size_t distance = 1; distance < transfers.stageZeroCores.size(); distance *= 2)
|
||||
++rounds;
|
||||
unsigned last = transfers.synchronizationRegisterCount - 1;
|
||||
for (auto [rank, core] : llvm::enumerate(transfers.downstreamCores)) {
|
||||
int64_t parent = rank ? transfers.downstreamCores[(rank - 1) / 2]
|
||||
: transfers.stageZeroCores.front();
|
||||
signal(core, parent, rank ? last - 1 : last - rounds, "restart-permission");
|
||||
}
|
||||
}
|
||||
|
||||
void PeriodicPlan::completionSynchronization() {
|
||||
unsigned rounds = 0;
|
||||
for (size_t distance = 1; distance < transfers.stageZeroCores.size(); distance *= 2)
|
||||
++rounds;
|
||||
unsigned last = transfers.synchronizationRegisterCount - 1;
|
||||
for (auto [rank, core] : llvm::enumerate(transfers.stageZeroCores))
|
||||
for (unsigned round = 0; round < rounds; ++round) {
|
||||
int64_t peer = transfers.stageZeroCores[
|
||||
(rank + (size_t{1} << round)) % transfers.stageZeroCores.size()];
|
||||
signal(core, peer, last - round, "barrier-signal");
|
||||
wait(core, last - round, 1, "barrier-wait");
|
||||
}
|
||||
if (!transfers.downstreamCores.empty()) {
|
||||
int64_t leader = transfers.stageZeroCores.front();
|
||||
wait(leader, last - rounds, 1, "restart-permission-wait");
|
||||
signal(leader, transfers.downstreamCores.front(), last, "restart-signal");
|
||||
}
|
||||
for (auto [rank, core] : llvm::enumerate(transfers.downstreamCores)) {
|
||||
wait(core, last, 1, "restart-wait");
|
||||
size_t first = 2 * rank + 1;
|
||||
size_t end = std::min(first + 2, transfers.downstreamCores.size());
|
||||
if (first < end)
|
||||
wait(core, last - 1, end - first, "restart-permission-wait");
|
||||
for (size_t child = first; child < end; ++child)
|
||||
signal(core, transfers.downstreamCores[child], last, "restart-signal");
|
||||
}
|
||||
}
|
||||
|
||||
bool PeriodicPlan::transfer(const ScheduledTransferSlice &slice, bool send) {
|
||||
const ExternalTransferFamily &family = *slice.family;
|
||||
auto type = mlir::dyn_cast<mlir::RankedTensorType>(family.requirement->publicationFragmentType);
|
||||
if (!type || !type.hasStaticShape() || !type.getElementType().isIntOrFloat()) {
|
||||
error = "transfer payload has no static byte size";
|
||||
return false;
|
||||
}
|
||||
Cost bits = std::min<Cost>(type.getElementType().getIntOrFloatBitWidth(),
|
||||
target.computeBitwidth);
|
||||
Cost payloadBits = checkedMultiply(static_cast<Cost>(type.getNumElements()), bits);
|
||||
Cost bytes = payloadBits / 8 + (payloadBits % 8 != 0);
|
||||
for (size_t offset = 0; offset < slice.transferCount; ++offset) {
|
||||
size_t index = slice.familyOffset + offset;
|
||||
int64_t source = family.sourceCores.valueAt(index);
|
||||
int64_t destination = family.targetCores.valueAt(index);
|
||||
int64_t core = send ? source : destination;
|
||||
int64_t channel = family.channelIds.valueAt(index);
|
||||
if (!family.hostRouted) {
|
||||
size_t begin = append(core, send ? "send-begin" : "receive-begin", 0, channel);
|
||||
size_t end = append(core, send ? "send-complete" : "receive-complete", 0, channel);
|
||||
if (!(send ? sends : receives).insert({channel, {begin, end, core, bytes}}).second) {
|
||||
error = "direct channel has multiple physical endpoints";
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
unsigned reg = family.eventRegisters.valueAt(index);
|
||||
if (send) {
|
||||
if (family.hostStoreFlags.valueAt(index)) {
|
||||
SharedMemoryDemand demand = target.getSharedMemoryDemand(bytes, 1, true);
|
||||
boundaryMemory += demand;
|
||||
Cost service = checkedAdd(target.getLocalMemoryServiceNs(bytes, false),
|
||||
checkedAdd(target.getSharedMemoryLinkServiceNs(bytes, core, false), demand.serviceNs));
|
||||
append(core, "host-store", service, family.hostOffsets.valueAt(index));
|
||||
}
|
||||
signal(core, destination, reg, "ready-signal");
|
||||
} else {
|
||||
wait(core, reg, family.waitValues.valueAt(index), "ready-wait");
|
||||
SharedMemoryDemand demand = target.getSharedMemoryDemand(bytes, 1, false);
|
||||
boundaryMemory += demand;
|
||||
Cost service = checkedAdd(target.getSharedMemoryLinkServiceNs(
|
||||
target.controlMessageBytes, core, false),
|
||||
checkedAdd(demand.serviceNs, checkedAdd(
|
||||
target.getSharedMemoryLinkServiceNs(
|
||||
target.sharedMemoryReadReturnsPayload ? bytes : 0, core, true),
|
||||
target.getLocalMemoryServiceNs(bytes, true))));
|
||||
append(core, "host-load", service, family.hostOffsets.valueAt(index));
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PeriodicPlan::boundary(const BoundaryProgram &program) {
|
||||
for (const BoundaryInstruction &instruction : program.instructions) {
|
||||
if (const auto *run = std::get_if<EmitSendRun>(&instruction)) {
|
||||
for (const auto &slice : run->slices)
|
||||
if (!transfer(slice, true))
|
||||
return false;
|
||||
} else if (const auto *run = std::get_if<EmitReceiveAssemblyRun>(&instruction)) {
|
||||
for (const auto &slice : run->slices)
|
||||
if (!transfer(slice, false))
|
||||
return false;
|
||||
} else if (const auto *reuse = std::get_if<EmitHostReuseWait>(&instruction)) {
|
||||
for (LaneInterval lanes : reuse->lanes.intervals())
|
||||
for (unsigned lane = lanes.begin; lane < lanes.end; ++lane)
|
||||
wait(program.key.first->cores[lane], reuse->eventRegisters.valueAt(lane),
|
||||
reuse->waitValues.valueAt(lane), "free-wait");
|
||||
}
|
||||
}
|
||||
return error.empty();
|
||||
}
|
||||
|
||||
bool PeriodicPlan::connect() {
|
||||
if (sends.size() != receives.size()) {
|
||||
error = "direct channel endpoint counts differ";
|
||||
return false;
|
||||
}
|
||||
for (const auto &[channel, send] : sends) {
|
||||
auto found = receives.find(channel);
|
||||
if (found == receives.end() || found->second.bytes != send.bytes) {
|
||||
error = "direct channel has no matching payload";
|
||||
return false;
|
||||
}
|
||||
const DirectEndpoint &receive = found->second;
|
||||
size_t permission = event(receive.core, "peer-permission", channel);
|
||||
edges.push_back({send.begin, permission,
|
||||
target.getLinkServiceNs(target.controlMessageBytes, send.core, receive.core), 0});
|
||||
edges.push_back({receive.begin, permission, 0, 0});
|
||||
edges.push_back({permission, send.end, checkedAdd(
|
||||
target.getLinkServiceNs(target.controlMessageBytes, receive.core, send.core),
|
||||
target.getLocalMemoryServiceNs(send.bytes, false)), 0});
|
||||
edges.push_back({send.end, receive.end, checkedAdd(
|
||||
target.getLinkServiceNs(send.bytes, send.core, receive.core),
|
||||
target.getLocalMemoryServiceNs(send.bytes, true)), 0});
|
||||
}
|
||||
if (signals.size() != waits.size()) {
|
||||
error = "signal and wait register sets differ";
|
||||
return false;
|
||||
}
|
||||
for (const auto &[key, pending] : waits) {
|
||||
auto found = signals.find(key);
|
||||
if (found == signals.end() || pending.count < 0
|
||||
|| found->second.size() != static_cast<size_t>(pending.count)) {
|
||||
error = "event register does not receive its exact static count";
|
||||
return false;
|
||||
}
|
||||
for (Signal signal : found->second)
|
||||
edges.push_back({signal.event, pending.event,
|
||||
target.getLinkServiceNs(target.controlMessageBytes, signal.core, key.first), 0});
|
||||
}
|
||||
for (size_t core = 0; core < active.size(); ++core)
|
||||
if (active[core])
|
||||
edges.push_back({tail[core], entry[core], 0, 1});
|
||||
return true;
|
||||
}
|
||||
|
||||
void PeriodicPlan::recordSynchronization(llvm::json::Object &report) const {
|
||||
llvm::json::Array registers;
|
||||
for (const auto &[key, pending] : waits) {
|
||||
llvm::json::Array sources;
|
||||
std::map<int64_t, int64_t> counts;
|
||||
auto found = signals.find(key);
|
||||
if (found != signals.end())
|
||||
for (Signal signal : found->second)
|
||||
++counts[signal.core];
|
||||
for (auto [core, count] : counts)
|
||||
sources.push_back(llvm::json::Object{{"core", core}, {"count", count}});
|
||||
registers.push_back(llvm::json::Object{{"core", key.first},
|
||||
{"register", key.second}, {"expected", pending.count},
|
||||
{"kind", events[pending.event].kind}, {"sources", std::move(sources)}});
|
||||
}
|
||||
report["event_registers"] = std::move(registers);
|
||||
}
|
||||
|
||||
bool PeriodicPlan::build(const ComputeGraph &graph,
|
||||
const ScheduledComputeMaterializationResult &materialization,
|
||||
const DeferredBoundaryPlan &boundaries) {
|
||||
if (!target.hasPeriodicTransferTiming()) {
|
||||
error = "target has no complete periodic communication timing contract";
|
||||
return false;
|
||||
}
|
||||
if (transfers.scheduled.empty() || transfers.stageZeroCores.empty()
|
||||
|| !transfers.synchronizationRegisterCount) {
|
||||
error = "periodic timing requires an active repeating pipeline body";
|
||||
return false;
|
||||
}
|
||||
for (auto [index, scheduled] : llvm::enumerate(transfers.scheduled)) {
|
||||
if (!materialization.materializedSchedules[index].runs.empty()
|
||||
&& scheduled.cores.size() != 1) {
|
||||
error = "compact compute runs require one physical core";
|
||||
return false;
|
||||
}
|
||||
for (int64_t core : scheduled.cores) {
|
||||
if (active[core]) {
|
||||
error = "physical core appears in multiple scheduled bodies";
|
||||
return false;
|
||||
}
|
||||
active[core] = true;
|
||||
tail[core] = entry[core] = event(core, "body-entry");
|
||||
}
|
||||
}
|
||||
entrySynchronization();
|
||||
llvm::DenseMap<std::pair<const ScheduledInfo *, unsigned>,
|
||||
const BoundaryProgram *> indexed;
|
||||
for (const BoundaryProgram &program : boundaries.boundaries)
|
||||
indexed[program.key] = &program;
|
||||
for (auto [recordIndex, record] : llvm::enumerate(materialization.materializedSchedules)) {
|
||||
const ScheduledInfo *scheduled = &transfers.scheduled[recordIndex];
|
||||
for (unsigned step = 0; step <= scheduled->stepCount; ++step) {
|
||||
if (const auto *program = indexed.lookup({scheduled, step}))
|
||||
if (!boundary(*program))
|
||||
return false;
|
||||
if (step == scheduled->stepCount)
|
||||
continue;
|
||||
auto appendCompute = [&](const ComputeInstance &instance, int64_t core) {
|
||||
auto found = graph.instanceToIndex.find(instance);
|
||||
if (found == graph.instanceToIndex.end()) {
|
||||
error = "scheduled compute instance is absent from the cost graph";
|
||||
return;
|
||||
}
|
||||
append(core, "compute", graph.nodes[found->second].cost, found->second);
|
||||
computeWork[core] = checkedAdd(computeWork[core], graph.nodes[found->second].cost);
|
||||
};
|
||||
if (!record.runs.empty()) {
|
||||
Cost cost = 0;
|
||||
for (const ComputeInstance &instance : record.runs[step].instances) {
|
||||
auto found = graph.instanceToIndex.find(instance);
|
||||
if (found == graph.instanceToIndex.end()) {
|
||||
error = "scheduled run instance is absent from the cost graph";
|
||||
return false;
|
||||
}
|
||||
cost = checkedAdd(cost, graph.nodes[found->second].cost);
|
||||
}
|
||||
append(scheduled->cores.front(), "compute-run", cost, step);
|
||||
int64_t core = scheduled->cores.front();
|
||||
computeWork[core] = checkedAdd(computeWork[core], cost);
|
||||
} else {
|
||||
for (auto [lane, instance] : llvm::enumerate(record.stepPlans[step].stepTuple.instances))
|
||||
appendCompute(instance, scheduled->cores[lane]);
|
||||
}
|
||||
}
|
||||
}
|
||||
completionSynchronization();
|
||||
return error.empty() && connect();
|
||||
}
|
||||
|
||||
static mlir::FailureOr<PeriodicDependencyEstimate> analyzePlan(PeriodicPlan &plan,
|
||||
const ComputeGraph &graph,
|
||||
const ScheduledComputeMaterializationResult &materialization,
|
||||
const DeferredBoundaryPlan &boundaries) {
|
||||
if (!plan.build(graph, materialization, boundaries))
|
||||
return mlir::failure();
|
||||
return analyzePeriodicDependencies(plan.events.size(), plan.edges, plan.error);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
llvm::json::Object getPeriodicScheduleReport(const ComputeGraph &graph,
|
||||
const ScheduledComputeMaterializationResult &materialization,
|
||||
const DeferredTransferPlan &transfers, const DeferredBoundaryPlan &boundaries,
|
||||
const PimInstructionTiming &target) {
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
PeriodicPlan plan(target, transfers);
|
||||
llvm::json::Object report{{"diagnostic_only", true},
|
||||
{"selection_eligible", false},
|
||||
{"timing_model", "serial compute chunks; uncontended communication; no issue or local contention model"}};
|
||||
report["omitted_effects"] = llvm::json::Array{
|
||||
"placement and timing of baseline memory accesses",
|
||||
"communication introduced after deferred realization, including final output collection",
|
||||
"instruction issue, execution-unit overlap and local-memory contention",
|
||||
"projection materialization, strided transfer splitting and load folding",
|
||||
"network injection queues and global-memory arbitration"};
|
||||
report["native_host_buffer_bytes"] = static_cast<int64_t>(transfers.pipelineHostBufferBytes);
|
||||
auto estimate = analyzePlan(plan, graph, materialization, boundaries);
|
||||
if (mlir::succeeded(estimate)) {
|
||||
plan.recordSynchronization(report);
|
||||
SharedMemoryDemand memory = graph.baselineMemory;
|
||||
memory += plan.boundaryMemory;
|
||||
report["recurrence_lower_ns"] = estimate->recurrenceLowerNs;
|
||||
report["recurrence_upper_ns"] = estimate->recurrenceUpperNs;
|
||||
report["within_generation_span_ns"] = static_cast<int64_t>(estimate->withinGenerationSpanNs);
|
||||
report["global_memory_service_ns"] = static_cast<int64_t>(memory.serviceNs);
|
||||
report["baseline_memory_service_ns"] = static_cast<int64_t>(graph.baselineMemory.serviceNs);
|
||||
report["boundary_memory_service_ns"] = static_cast<int64_t>(plan.boundaryMemory.serviceNs);
|
||||
report["boundary_read_bytes"] = static_cast<int64_t>(plan.boundaryMemory.readBytes);
|
||||
report["boundary_write_bytes"] = static_cast<int64_t>(plan.boundaryMemory.writeBytes);
|
||||
report["boundary_read_requests"] = static_cast<int64_t>(plan.boundaryMemory.readRequests);
|
||||
report["boundary_write_requests"] = static_cast<int64_t>(plan.boundaryMemory.writeRequests);
|
||||
Cost coreWork = *std::max_element(plan.computeWork.begin(), plan.computeWork.end());
|
||||
report["maximum_core_compute_ns"] = static_cast<int64_t>(coreWork);
|
||||
report["interval_estimate_ns"] = std::max({estimate->recurrenceUpperNs,
|
||||
static_cast<double>(memory.serviceNs), static_cast<double>(coreWork)});
|
||||
report["relaxation_rounds"] = static_cast<int64_t>(estimate->relaxationRounds);
|
||||
llvm::json::Array cycle;
|
||||
std::map<llvm::StringRef, int64_t> kinds;
|
||||
std::map<int64_t, Cost> coreDelays;
|
||||
std::map<std::pair<int64_t, int64_t>, Cost> linkDelays;
|
||||
Cost delay = 0, distance = 0;
|
||||
for (size_t index : estimate->criticalCycle) {
|
||||
const auto &edge = plan.edges[index];
|
||||
const Event &source = plan.events[edge.source], &destination = plan.events[edge.target];
|
||||
delay = checkedAdd(delay, edge.delayNs);
|
||||
distance = checkedAdd(distance, static_cast<Cost>(edge.distance));
|
||||
++kinds[destination.kind];
|
||||
coreDelays[destination.core] = checkedAdd(coreDelays[destination.core], edge.delayNs);
|
||||
if (source.core != destination.core)
|
||||
linkDelays[{source.core, destination.core}] = checkedAdd(
|
||||
linkDelays[{source.core, destination.core}], edge.delayNs);
|
||||
if (cycle.size() < 128)
|
||||
cycle.push_back(llvm::json::Object{{"source_core", source.core},
|
||||
{"source_kind", source.kind}, {"target_core", destination.core},
|
||||
{"target_kind", destination.kind}, {"identity", destination.identity},
|
||||
{"delay_ns", static_cast<int64_t>(edge.delayNs)},
|
||||
{"distance", edge.distance}});
|
||||
}
|
||||
llvm::json::Object counts;
|
||||
for (auto [kind, count] : kinds)
|
||||
counts[kind] = count;
|
||||
report["critical_cycle"] = std::move(cycle);
|
||||
report["critical_cycle_event_counts"] = std::move(counts);
|
||||
report["critical_cycle_edges"] = static_cast<int64_t>(estimate->criticalCycle.size());
|
||||
report["critical_cycle_delay_ns"] = static_cast<int64_t>(delay);
|
||||
report["critical_cycle_distance"] = static_cast<int64_t>(distance);
|
||||
llvm::json::Array cores, links;
|
||||
for (auto [core, ns] : coreDelays)
|
||||
cores.push_back(llvm::json::Object{{"core", core}, {"delay_ns", static_cast<int64_t>(ns)}});
|
||||
for (auto [pair, ns] : linkDelays)
|
||||
links.push_back(llvm::json::Object{{"source", pair.first}, {"target", pair.second},
|
||||
{"delay_ns", static_cast<int64_t>(ns)}});
|
||||
report["critical_cycle_cores"] = std::move(cores);
|
||||
report["critical_cycle_links"] = std::move(links);
|
||||
}
|
||||
report["status"] = plan.error.empty() ? "estimated" : "unavailable";
|
||||
if (!plan.error.empty())
|
||||
report["reason"] = plan.error;
|
||||
report["events"] = static_cast<int64_t>(plan.events.size());
|
||||
report["edges"] = static_cast<int64_t>(plan.edges.size());
|
||||
llvm::json::Object eventCounts;
|
||||
std::map<llvm::StringRef, int64_t> counts;
|
||||
for (const Event &event : plan.events)
|
||||
++counts[event.kind];
|
||||
for (auto [kind, count] : counts)
|
||||
eventCounts[kind] = count;
|
||||
report["event_counts"] = std::move(eventCounts);
|
||||
report["analysis_wall_ms"] = std::chrono::duration<double, std::milli>(
|
||||
std::chrono::steady_clock::now() - start).count();
|
||||
return report;
|
||||
}
|
||||
|
||||
void dumpPeriodicScheduleEstimate(const ComputeGraph &graph,
|
||||
const ScheduledComputeMaterializationResult &materialization,
|
||||
const DeferredTransferPlan &transfers, const DeferredBoundaryPlan &boundaries,
|
||||
const PimInstructionTiming &target) {
|
||||
auto file = openDialectDumpFileWithExtension("pipeline_periodic", "/reports", "json");
|
||||
if (!file.is_open())
|
||||
return;
|
||||
auto report = getPeriodicScheduleReport(graph, materialization, transfers,
|
||||
boundaries, target);
|
||||
llvm::raw_os_ostream os(file);
|
||||
os << llvm::formatv("{0:2}\n", llvm::json::Value(std::move(report)));
|
||||
}
|
||||
|
||||
} // namespace onnx_mlir
|
||||
@@ -0,0 +1,22 @@
|
||||
#pragma once
|
||||
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/DeferredBoundaryPlanning.hpp"
|
||||
#include "src/Accelerators/PIM/Dialect/Spatial/Passes/Transforms/MergeComputeNodes/Scheduling/ComputeGraph.hpp"
|
||||
#include "llvm/Support/JSON.h"
|
||||
|
||||
namespace onnx_mlir {
|
||||
namespace spatial { struct ScheduledComputeMaterializationResult; }
|
||||
struct PimInstructionTiming;
|
||||
|
||||
llvm::json::Object getPeriodicScheduleReport(const spatial::ComputeGraph &graph,
|
||||
const spatial::ScheduledComputeMaterializationResult &materialization,
|
||||
const spatial::DeferredTransferPlan &transfers, const spatial::DeferredBoundaryPlan &boundaries,
|
||||
const PimInstructionTiming &target);
|
||||
|
||||
// Read-only diagnostics over the final physical transfer and synchronization plan.
|
||||
void dumpPeriodicScheduleEstimate(const spatial::ComputeGraph &graph,
|
||||
const spatial::ScheduledComputeMaterializationResult &materialization,
|
||||
const spatial::DeferredTransferPlan &transfers, const spatial::DeferredBoundaryPlan &boundaries,
|
||||
const PimInstructionTiming &target);
|
||||
|
||||
} // namespace onnx_mlir
|
||||
@@ -39,6 +39,7 @@ add_pim_library(SpatialOps
|
||||
Passes/Transforms/MergeComputeNodes/Scheduling/PipelineScheduling.cpp
|
||||
Passes/Transforms/MergeComputeNodes/Scheduling/PipelineWorkloadPreparation.cpp
|
||||
Passes/Transforms/MergeComputeNodes/Scheduling/ScheduleEvaluation.cpp
|
||||
Passes/Transforms/MergeComputeNodes/Scheduling/PeriodicDependencies.cpp
|
||||
Passes/Transforms/TrivialGraphComputeMergePass.cpp
|
||||
|
||||
EXCLUDE_FROM_OM_LIBS
|
||||
|
||||
+18
-2
@@ -465,8 +465,20 @@ LogicalResult prepareMultiCpuTupleInput(OpBuilder &, Location loc, Value input,
|
||||
|
||||
LogicalResult materializeDeferredPayloadDemands(OpBuilder &builder, Location loc, Block &body,
|
||||
ArrayRef<DeferredInputPlan> plans, IRMapping &mapper,
|
||||
llvm::SmallPtrSetImpl<Operation *> &absorbed) {
|
||||
llvm::SmallPtrSetImpl<Operation *> &absorbed,
|
||||
bool deterministicOrder) {
|
||||
// Deferred demand order must not depend on allocator addresses.
|
||||
DenseMap<Value, unsigned> valueOrder;
|
||||
if (deterministicOrder) {
|
||||
for (BlockArgument argument : body.getArguments())
|
||||
valueOrder.try_emplace(argument, valueOrder.size());
|
||||
body.walk([&](Operation *op) {
|
||||
for (Value result : op->getResults())
|
||||
valueOrder.try_emplace(result, valueOrder.size());
|
||||
});
|
||||
}
|
||||
for (const DeferredInputPlan &plan : plans) {
|
||||
valueOrder.try_emplace(plan.graphInput, valueOrder.size());
|
||||
if (plan.availableValue) { mapper.map(plan.graphInput, plan.availableValue); continue; }
|
||||
SmallVector<Value> roots;
|
||||
bool needsIdentity = false;
|
||||
@@ -498,7 +510,11 @@ LogicalResult materializeDeferredPayloadDemands(OpBuilder &builder, Location loc
|
||||
}
|
||||
}
|
||||
if (needsIdentity) roots.push_back(plan.graphInput);
|
||||
llvm::sort(roots, [](Value a, Value b) { return a.getAsOpaquePointer() < b.getAsOpaquePointer(); });
|
||||
llvm::sort(roots, [&](Value a, Value b) {
|
||||
if (!deterministicOrder) return a.getAsOpaquePointer() < b.getAsOpaquePointer();
|
||||
assert(valueOrder.count(a) && valueOrder.count(b));
|
||||
return valueOrder.lookup(a) < valueOrder.lookup(b);
|
||||
});
|
||||
roots.erase(std::unique(roots.begin(), roots.end()), roots.end());
|
||||
Value sharedSource;
|
||||
if (!plan.blueprint) {
|
||||
|
||||
+2
-1
@@ -47,7 +47,8 @@ LogicalResult materializeDeferredPayloadDemands(OpBuilder &builder, Location loc
|
||||
Block &graphBody,
|
||||
ArrayRef<DeferredInputPlan> plans,
|
||||
IRMapping &mapper,
|
||||
llvm::SmallPtrSetImpl<Operation *> &absorbed);
|
||||
llvm::SmallPtrSetImpl<Operation *> &absorbed,
|
||||
bool deterministicOrder);
|
||||
|
||||
} // namespace spatial
|
||||
} // namespace onnx_mlir
|
||||
|
||||
+4
-1
@@ -148,7 +148,8 @@ static LogicalResult verifyDominance(func::FuncOp funcOp) {
|
||||
LogicalResult realizeDeferredCommunication(func::FuncOp funcOp,
|
||||
const ScheduledComputeMaterializationResult& materialization,
|
||||
const SchedulingTarget& target,
|
||||
size_t pipelineStages) {
|
||||
size_t pipelineStages,
|
||||
const ComputeGraph *costGraph) {
|
||||
IRRewriter rewriter(funcOp.getContext());
|
||||
eraseUnusedIdentityDeferredCommunications(funcOp, rewriter);
|
||||
|
||||
@@ -172,6 +173,8 @@ LogicalResult realizeDeferredCommunication(func::FuncOp funcOp,
|
||||
*transfers, *schedule, target.synchronizationRegisterCount);
|
||||
if (failed(boundaries))
|
||||
return funcOp.emitOpError("phase 2 failed to build sparse boundary programs");
|
||||
if (pipelineStages > 1 && costGraph && target.reportPeriodicSchedule)
|
||||
target.reportPeriodicSchedule(*costGraph, materialization, *transfers, *boundaries);
|
||||
|
||||
if (failed(retargetDeferredPublications(funcOp, *transfers))
|
||||
|| failed(replaceFinalGraphPublications(funcOp, *transfers)))
|
||||
|
||||
+3
-1
@@ -6,10 +6,12 @@ namespace onnx_mlir::spatial {
|
||||
|
||||
struct ScheduledComputeMaterializationResult;
|
||||
struct SchedulingTarget;
|
||||
struct ComputeGraph;
|
||||
|
||||
mlir::LogicalResult realizeDeferredCommunication(mlir::func::FuncOp funcOp,
|
||||
const ScheduledComputeMaterializationResult& materialization,
|
||||
const SchedulingTarget& target,
|
||||
size_t pipelineStages = 1);
|
||||
size_t pipelineStages = 1,
|
||||
const ComputeGraph *costGraph = nullptr);
|
||||
|
||||
} // namespace onnx_mlir::spatial
|
||||
|
||||
+4
-4
@@ -239,7 +239,7 @@ static LogicalResult materializeResultfulBatchRun(
|
||||
|
||||
Block &source = batch.getBody().front();
|
||||
llvm::SmallPtrSet<Operation *, 32> absorbed;
|
||||
if (failed(materializeDeferredPayloadDemands(builder, bodyLoc, source, inputPlans, mapper, absorbed)))
|
||||
if (failed(materializeDeferredPayloadDemands(builder, bodyLoc, source, inputPlans, mapper, absorbed, !schedule.processorStages.empty())))
|
||||
return failure();
|
||||
for (Operation &op : source.without_terminator())
|
||||
if (!absorbed.contains(&op))
|
||||
@@ -334,7 +334,7 @@ static LogicalResult materializeSingleCpuPeftClass(
|
||||
inputPlans.push_back(std::move(plan));
|
||||
}
|
||||
llvm::SmallPtrSet<Operation *, 32> absorbed;
|
||||
if (failed(materializeDeferredPayloadDemands(rewriter, compute.getLoc(), compute.getBody().front(), inputPlans, mapper, absorbed)))
|
||||
if (failed(materializeDeferredPayloadDemands(rewriter, compute.getLoc(), compute.getBody().front(), inputPlans, mapper, absorbed, !schedule.processorStages.empty())))
|
||||
return failure();
|
||||
cloneComputeBody(rewriter, compute.getBody().front(), mapper, yieldedValues, absorbed);
|
||||
} else {
|
||||
@@ -589,7 +589,7 @@ static LogicalResult materializeMultiCpuPeftClass(
|
||||
}
|
||||
SmallVector<Value> yieldedValues;
|
||||
llvm::SmallPtrSet<Operation *, 32> absorbed;
|
||||
if (failed(materializeDeferredPayloadDemands(rewriter, compute.getLoc(), compute.getBody().front(), inputPlans, mapper, absorbed)))
|
||||
if (failed(materializeDeferredPayloadDemands(rewriter, compute.getLoc(), compute.getBody().front(), inputPlans, mapper, absorbed, !schedule.processorStages.empty())))
|
||||
return failure();
|
||||
cloneComputeBody(rewriter, compute.getBody().front(), mapper, yieldedValues, absorbed);
|
||||
for (Value yielded : yieldedValues) {
|
||||
@@ -668,7 +668,7 @@ static LogicalResult materializeMultiCpuPeftClass(
|
||||
for (unsigned index = 0; index < batch.getNumResults(); ++index)
|
||||
mapper.map(*batch.getOutputArgument(index), iterArgs[index]);
|
||||
llvm::SmallPtrSet<Operation *, 32> absorbed;
|
||||
if (failed(materializeDeferredPayloadDemands(builder, bodyLoc, batch.getBody().front(), inputPlans, mapper, absorbed)))
|
||||
if (failed(materializeDeferredPayloadDemands(builder, bodyLoc, batch.getBody().front(), inputPlans, mapper, absorbed, !schedule.processorStages.empty())))
|
||||
return failure();
|
||||
for (Operation &op : batch.getBody().front().without_terminator())
|
||||
if (!absorbed.contains(&op))
|
||||
|
||||
@@ -79,6 +79,13 @@ void dumpScheduledComputeReport(ModuleOp moduleOp, func::FuncOp funcOp, const Me
|
||||
std::fstream file = openDialectDumpFileWithExtension("spatial3_scheduled_no_comm", "/reports", "txt");
|
||||
if (!file.is_open()) return;
|
||||
llvm::raw_os_ostream os(file);
|
||||
writeScheduledComputeReport(os, moduleOp, funcOp, schedule, peftClassPlans, records);
|
||||
}
|
||||
|
||||
void writeScheduledComputeReport(raw_ostream &os, ModuleOp moduleOp, func::FuncOp funcOp,
|
||||
const MergeScheduleResult &schedule,
|
||||
const llvm::MapVector<size_t, PeftClassPlan> &peftClassPlans,
|
||||
ArrayRef<ScheduledMaterializationRecord> records) {
|
||||
OpPrintingFlags flags;
|
||||
flags.elideLargeElementsAttrs().enableDebugInfo(false, false).assumeVerified();
|
||||
AsmState asmState(moduleOp.getOperation(), flags);
|
||||
|
||||
@@ -5,6 +5,12 @@
|
||||
namespace onnx_mlir {
|
||||
namespace spatial {
|
||||
|
||||
void writeScheduledComputeReport(llvm::raw_ostream &os, ModuleOp moduleOp,
|
||||
func::FuncOp funcOp,
|
||||
const MergeScheduleResult &schedule,
|
||||
const llvm::MapVector<size_t, PeftClassPlan> &peftClassPlans,
|
||||
ArrayRef<ScheduledMaterializationRecord> materializedSchedules);
|
||||
|
||||
void dumpScheduledComputeReport(ModuleOp moduleOp,
|
||||
func::FuncOp funcOp,
|
||||
const MergeScheduleResult &schedule,
|
||||
|
||||
+152
-111
@@ -1,5 +1,6 @@
|
||||
#include "mlir/Pass/Pass.h"
|
||||
|
||||
#include "ScheduledSpatialPasses.hpp"
|
||||
#include "DeferredCommunicationRealization.hpp"
|
||||
#include "ScheduledComputeReport.hpp"
|
||||
#include "ScheduledComputeVerification.hpp"
|
||||
@@ -40,9 +41,9 @@ struct ScheduleAndRealizeSpatialPass final
|
||||
ScheduleAndRealizeSpatialPass() = default;
|
||||
ScheduleAndRealizeSpatialPass(const SchedulingTarget& target,
|
||||
SpatialDataflowExportStage exportStage,
|
||||
size_t pipelineStages)
|
||||
size_t pipelineStages, bool periodicDiagnostics)
|
||||
: target(target), exportStage(exportStage),
|
||||
pipelineStages(pipelineStages), hasTarget(true) {}
|
||||
pipelineStages(pipelineStages), periodicDiagnostics(periodicDiagnostics), hasTarget(true) {}
|
||||
|
||||
StringRef getArgument() const override { return "schedule-and-realize-spatial"; }
|
||||
StringRef getDescription() const override {
|
||||
@@ -64,113 +65,10 @@ struct ScheduleAndRealizeSpatialPass final
|
||||
signalPassFailure();
|
||||
return;
|
||||
}
|
||||
auto entry = requireEntry(moduleOp);
|
||||
if (failed(entry)) {
|
||||
signalPassFailure();
|
||||
return;
|
||||
}
|
||||
func::FuncOp entryFunc = *entry;
|
||||
|
||||
ComputeGraph scheduledGraph;
|
||||
MergeScheduleResult schedule;
|
||||
for (;;) {
|
||||
auto graph = buildComputeGraph(entryFunc, target);
|
||||
if (failed(graph)) {
|
||||
signalPassFailure();
|
||||
return;
|
||||
}
|
||||
scheduledGraph = std::move(*graph);
|
||||
std::string pipelineError;
|
||||
if (pipelineStages > 1) {
|
||||
FailureOr<PipelineWorkloadPreparation> preparation =
|
||||
preparePipelineWorkload(
|
||||
scheduledGraph, pipelineStages, target, pipelineError);
|
||||
if (failed(preparation)) {
|
||||
moduleOp.emitError() << pipelineError;
|
||||
signalPassFailure();
|
||||
return;
|
||||
}
|
||||
if (*preparation == PipelineWorkloadPreparation::Changed)
|
||||
continue;
|
||||
}
|
||||
if (pipelineStages == 1) {
|
||||
MergeSchedulingAnalysis analysis(
|
||||
scheduledGraph, target, entryFunc.getContext(), pipelineError);
|
||||
if (failed(analysis.getResult())) {
|
||||
moduleOp.emitError() << pipelineError;
|
||||
signalPassFailure();
|
||||
return;
|
||||
}
|
||||
schedule = std::move(*analysis.getResult());
|
||||
break;
|
||||
}
|
||||
if (succeeded(runPipelineScheduler(
|
||||
scheduledGraph, schedule, pipelineStages, target, pipelineError)))
|
||||
break;
|
||||
moduleOp.emitError() << pipelineError;
|
||||
signalPassFailure();
|
||||
return;
|
||||
}
|
||||
PatternRewriter rewriter(moduleOp.getContext());
|
||||
FailureOr<ScheduledComputeMaterializationResult> materialization =
|
||||
materializeScheduledCompute(entryFunc, schedule, rewriter);
|
||||
if (failed(materialization)) {
|
||||
signalPassFailure();
|
||||
return;
|
||||
}
|
||||
ScheduledComputeMaterializationResult materializationResult = std::move(*materialization);
|
||||
|
||||
if (failed(verifyMaterializedScheduleMapping(
|
||||
entryFunc, schedule, materializationResult.peftClassPlans,
|
||||
materializationResult.graphComputeToBlockMap,
|
||||
materializationResult.materializedSchedules))
|
||||
|| failed(verifyDeferredTransferPhase1Invariants(entryFunc))
|
||||
|| failed(verifyScheduledMaterializationRecords(materializationResult.materializedSchedules))
|
||||
|| failed(verifyScheduledSpatialInvariants(entryFunc))) {
|
||||
moduleOp.emitError("scheduled Spatial phase verification failed");
|
||||
signalPassFailure();
|
||||
return;
|
||||
}
|
||||
|
||||
dumpModule(moduleOp, "spatial3_scheduled_no_comm", /*assumeVerified=*/true);
|
||||
if (shouldExportSpatialDataflowStage(exportStage, SpatialDataflowExportStage::Spatial3)
|
||||
&& failed(exportSpatialDataflowCsvScheduled(
|
||||
entryFunc, materializationResult.materializedSchedules,
|
||||
"spatial3_scheduled_no_comm", "spatial3"))) {
|
||||
signalPassFailure();
|
||||
return;
|
||||
}
|
||||
dumpScheduledComputeReport(
|
||||
moduleOp, entryFunc, schedule, materializationResult.peftClassPlans,
|
||||
materializationResult.materializedSchedules);
|
||||
|
||||
if (failed(realizeDeferredCommunication(
|
||||
entryFunc, materializationResult, target, pipelineStages))) {
|
||||
moduleOp.emitError("Spatial communication realization failed");
|
||||
signalPassFailure();
|
||||
return;
|
||||
}
|
||||
|
||||
bool deferredRemains = false;
|
||||
entryFunc.walk([&](SpatDeferredCommunicationOp deferred) {
|
||||
if (deferredRemains)
|
||||
return;
|
||||
deferred.emitOpError("realized Spatial graph still contains deferred communication");
|
||||
deferredRemains = true;
|
||||
});
|
||||
if (deferredRemains
|
||||
|| failed(verifyScheduledResultsLive(materializationResult.materializedSchedules))
|
||||
|| failed(verifyScheduledSpatialInvariants(entryFunc))) {
|
||||
moduleOp.emitError("realized Spatial communication verification failed");
|
||||
signalPassFailure();
|
||||
return;
|
||||
}
|
||||
|
||||
dumpModule(moduleOp, "spatial4_scheduled", /*assumeVerified=*/true);
|
||||
if (shouldExportSpatialDataflowStage(exportStage, SpatialDataflowExportStage::Spatial4)
|
||||
&& failed(exportSpatialDataflowCsvScheduled(
|
||||
entryFunc, materializationResult.materializedSchedules,
|
||||
"spatial4_scheduled", "spatial4")))
|
||||
auto prepared = prepareSpatialSchedules(moduleOp, target, pipelineStages, false);
|
||||
if (failed(prepared) || failed(realizeSpatialSchedule(moduleOp,
|
||||
prepared->candidates.front(), target, pipelineStages, exportStage,
|
||||
periodicDiagnostics ? &prepared->graph : nullptr)))
|
||||
signalPassFailure();
|
||||
}
|
||||
|
||||
@@ -178,11 +76,154 @@ private:
|
||||
SchedulingTarget target;
|
||||
SpatialDataflowExportStage exportStage = SpatialDataflowExportStage::None;
|
||||
size_t pipelineStages = 1;
|
||||
bool periodicDiagnostics = false;
|
||||
bool hasTarget = false;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
FailureOr<PreparedSpatialSchedules> prepareSpatialSchedules(ModuleOp moduleOp,
|
||||
const SchedulingTarget &target, size_t pipelineStages, bool collectCandidates) {
|
||||
if (!hasValidTarget(target) || !PipelineCoreLayout(target.processorCount, pipelineStages).isValid()
|
||||
|| (pipelineStages > 1 && !target.synchronizationRegisterCount))
|
||||
return moduleOp.emitError("Spatial scheduling requires an explicit valid target and pipeline layout"), failure();
|
||||
auto entry = requireEntry(moduleOp);
|
||||
if (failed(entry)) return failure();
|
||||
auto entryFunc = *entry;
|
||||
PreparedSpatialSchedules prepared;
|
||||
auto &scheduledGraph = prepared.graph;
|
||||
MergeScheduleResult schedule;
|
||||
for (;;) {
|
||||
auto graph = buildComputeGraph(entryFunc, target);
|
||||
if (failed(graph)) {
|
||||
return failure();
|
||||
}
|
||||
scheduledGraph = std::move(*graph);
|
||||
std::string pipelineError;
|
||||
if (pipelineStages > 1) {
|
||||
FailureOr<PipelineWorkloadPreparation> preparation =
|
||||
preparePipelineWorkload(
|
||||
scheduledGraph, pipelineStages, target, pipelineError);
|
||||
if (failed(preparation)) {
|
||||
moduleOp.emitError() << pipelineError;
|
||||
return failure();
|
||||
}
|
||||
if (*preparation == PipelineWorkloadPreparation::Changed)
|
||||
continue;
|
||||
}
|
||||
if (pipelineStages == 1) {
|
||||
MergeSchedulingAnalysis analysis(
|
||||
scheduledGraph, target, entryFunc.getContext(), pipelineError);
|
||||
if (failed(analysis.getResult())) {
|
||||
moduleOp.emitError() << pipelineError;
|
||||
return failure();
|
||||
}
|
||||
schedule = std::move(*analysis.getResult());
|
||||
break;
|
||||
}
|
||||
if (succeeded(runPipelineScheduler(
|
||||
scheduledGraph, schedule, pipelineStages, target, pipelineError, collectCandidates ? &prepared.candidates : nullptr)))
|
||||
break;
|
||||
moduleOp.emitError() << pipelineError;
|
||||
return failure();
|
||||
}
|
||||
|
||||
if (prepared.candidates.empty()) prepared.candidates.push_back(std::move(schedule));
|
||||
return prepared;
|
||||
}
|
||||
|
||||
LogicalResult realizeSpatialSchedule(ModuleOp moduleOp,
|
||||
const MergeScheduleResult &schedule, const SchedulingTarget &target,
|
||||
size_t pipelineStages, SpatialDataflowExportStage exportStage,
|
||||
const ComputeGraph *costGraph, std::string *scheduleReport) {
|
||||
auto entry = requireEntry(moduleOp);
|
||||
if (failed(entry)) return failure();
|
||||
auto entryFunc = *entry;
|
||||
PatternRewriter rewriter(moduleOp.getContext());
|
||||
FailureOr<ScheduledComputeMaterializationResult> materialization =
|
||||
materializeScheduledCompute(entryFunc, schedule, rewriter);
|
||||
if (failed(materialization)) {
|
||||
return failure();
|
||||
}
|
||||
ScheduledComputeMaterializationResult materializationResult = std::move(*materialization);
|
||||
|
||||
if (failed(verifyMaterializedScheduleMapping(
|
||||
entryFunc, schedule, materializationResult.peftClassPlans,
|
||||
materializationResult.graphComputeToBlockMap,
|
||||
materializationResult.materializedSchedules))
|
||||
|| failed(verifyDeferredTransferPhase1Invariants(entryFunc))
|
||||
|| failed(verifyScheduledMaterializationRecords(materializationResult.materializedSchedules))
|
||||
|| failed(verifyScheduledSpatialInvariants(entryFunc))) {
|
||||
moduleOp.emitError("scheduled Spatial phase verification failed");
|
||||
return failure();
|
||||
}
|
||||
|
||||
dumpModule(moduleOp, "spatial3_scheduled_no_comm", /*assumeVerified=*/true);
|
||||
if (shouldExportSpatialDataflowStage(exportStage, SpatialDataflowExportStage::Spatial3)
|
||||
&& failed(exportSpatialDataflowCsvScheduled(
|
||||
entryFunc, materializationResult.materializedSchedules,
|
||||
"spatial3_scheduled_no_comm", "spatial3"))) {
|
||||
return failure();
|
||||
}
|
||||
if (scheduleReport) {
|
||||
llvm::raw_string_ostream os(*scheduleReport);
|
||||
writeScheduledComputeReport(os, moduleOp, entryFunc, schedule,
|
||||
materializationResult.peftClassPlans, materializationResult.materializedSchedules);
|
||||
} else {
|
||||
dumpScheduledComputeReport(
|
||||
moduleOp, entryFunc, schedule, materializationResult.peftClassPlans,
|
||||
materializationResult.materializedSchedules);
|
||||
}
|
||||
|
||||
if (failed(realizeDeferredCommunication(
|
||||
entryFunc, materializationResult, target, pipelineStages, costGraph))) {
|
||||
moduleOp.emitError("Spatial communication realization failed");
|
||||
return failure();
|
||||
}
|
||||
|
||||
bool deferredRemains = false;
|
||||
entryFunc.walk([&](SpatDeferredCommunicationOp deferred) {
|
||||
if (deferredRemains)
|
||||
return;
|
||||
deferred.emitOpError("realized Spatial graph still contains deferred communication");
|
||||
deferredRemains = true;
|
||||
});
|
||||
if (deferredRemains
|
||||
|| failed(verifyScheduledResultsLive(materializationResult.materializedSchedules))
|
||||
|| failed(verifyScheduledSpatialInvariants(entryFunc))) {
|
||||
moduleOp.emitError("realized Spatial communication verification failed");
|
||||
return failure();
|
||||
}
|
||||
|
||||
dumpModule(moduleOp, "spatial4_scheduled", /*assumeVerified=*/true);
|
||||
if (shouldExportSpatialDataflowStage(exportStage, SpatialDataflowExportStage::Spatial4)
|
||||
&& failed(exportSpatialDataflowCsvScheduled(
|
||||
entryFunc, materializationResult.materializedSchedules,
|
||||
"spatial4_scheduled", "spatial4")))
|
||||
return failure();
|
||||
return success();
|
||||
}
|
||||
|
||||
MergeScheduleResult remapSpatialSchedule(const MergeScheduleResult &schedule,
|
||||
const IRMapping &mapping) {
|
||||
MergeScheduleResult result = schedule;
|
||||
auto remap = [&](ComputeInstance instance) {
|
||||
instance.op = mapping.lookup(instance.op);
|
||||
return instance;
|
||||
};
|
||||
for (auto &instance : result.dominanceOrderCompute) instance = remap(instance);
|
||||
result.computeToCpuMap.clear();
|
||||
result.computeToCpuSlotMap.clear();
|
||||
result.computeToAestMap.clear();
|
||||
result.isLastComputeOfCpu.clear();
|
||||
for (auto [instance, cpu] : schedule.computeToCpuMap) result.computeToCpuMap[remap(instance)] = cpu;
|
||||
for (auto [instance, slot] : schedule.computeToCpuSlotMap) result.computeToCpuSlotMap[remap(instance)] = slot;
|
||||
for (auto [instance, start] : schedule.computeToAestMap) result.computeToAestMap[remap(instance)] = start;
|
||||
for (auto instance : schedule.isLastComputeOfCpu) result.isLastComputeOfCpu.insert(remap(instance));
|
||||
for (auto &[cpu, instance] : result.cpuToLastComputeMap) instance = remap(instance);
|
||||
return result;
|
||||
}
|
||||
|
||||
std::unique_ptr<Pass> createScheduleAndRealizeSpatialPass() {
|
||||
return std::make_unique<ScheduleAndRealizeSpatialPass>();
|
||||
}
|
||||
@@ -190,9 +231,9 @@ std::unique_ptr<Pass> createScheduleAndRealizeSpatialPass() {
|
||||
std::unique_ptr<Pass> createScheduleAndRealizeSpatialPass(
|
||||
const SchedulingTarget& target,
|
||||
SpatialDataflowExportStage exportStage,
|
||||
size_t pipelineStages) {
|
||||
size_t pipelineStages, bool periodicDiagnostics) {
|
||||
return std::make_unique<ScheduleAndRealizeSpatialPass>(
|
||||
target, exportStage, pipelineStages);
|
||||
target, exportStage, pipelineStages, periodicDiagnostics);
|
||||
}
|
||||
|
||||
} // namespace spatial
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
#include "Scheduling/ComputeGraph.hpp"
|
||||
#include "Scheduling/MergeSchedule.hpp"
|
||||
#include "SpatialDataflowCsvExporter.hpp"
|
||||
#include "mlir/IR/BuiltinOps.h"
|
||||
#include "mlir/IR/IRMapping.h"
|
||||
|
||||
namespace onnx_mlir::spatial {
|
||||
struct PreparedSpatialSchedules {
|
||||
ComputeGraph graph;
|
||||
std::vector<MergeScheduleResult> candidates;
|
||||
};
|
||||
|
||||
mlir::FailureOr<PreparedSpatialSchedules> prepareSpatialSchedules(
|
||||
mlir::ModuleOp module, const SchedulingTarget &target,
|
||||
size_t pipelineStages, bool collectCandidates);
|
||||
mlir::LogicalResult realizeSpatialSchedule(mlir::ModuleOp module,
|
||||
const MergeScheduleResult &schedule, const SchedulingTarget &target,
|
||||
size_t pipelineStages, SpatialDataflowExportStage exportStage,
|
||||
const ComputeGraph *costGraph = nullptr, std::string *scheduleReport = nullptr);
|
||||
MergeScheduleResult remapSpatialSchedule(const MergeScheduleResult &schedule,
|
||||
const mlir::IRMapping &mapping);
|
||||
} // namespace onnx_mlir::spatial
|
||||
+1
-23
@@ -184,29 +184,7 @@ struct SchedulerCostModel {
|
||||
}
|
||||
|
||||
Cost getMatrixComputeLatency(Cost inputBitwidth) const {
|
||||
Cost inputTimes = ceilDiv(inputBitwidth, target.matrixInputResolutionBits);
|
||||
Cost inputPasses = ceilDiv(target.matrixRows, target.matrixInputParallelism);
|
||||
Cost outputPasses = ceilDiv(target.matrixColumns, target.matrixOutputParallelism);
|
||||
Cost readCycles = ceilDiv(target.matrixReadLatencyNs, target.matrixPeriodNs);
|
||||
Cost frontStage = target.matrixInputBufferLatencyCycles + target.matrixInputLatencyCycles
|
||||
+ readCycles + target.matrixSampleLatencyCycles;
|
||||
Cost backPipe = std::max(target.matrixOutputLatencyCycles,
|
||||
checkedAdd(target.matrixShiftLatencyCycles,
|
||||
target.matrixBufferLatencyCycles));
|
||||
Cost backStage = checkedAdd(
|
||||
checkedAdd(target.matrixOutputLatencyCycles, target.matrixShiftLatencyCycles),
|
||||
target.matrixBufferLatencyCycles);
|
||||
backStage = checkedAdd(backStage, checkedMultiply(outputPasses - 1, backPipe));
|
||||
Cost totalTimes = checkedMultiply(inputTimes, inputPasses);
|
||||
if (!target.matrixPipeline)
|
||||
return checkedMultiply(
|
||||
checkedMultiply(checkedAdd(frontStage, backStage), totalTimes),
|
||||
target.matrixPeriodNs);
|
||||
Cost stagePipe = std::max(frontStage, backStage);
|
||||
return checkedMultiply(
|
||||
checkedAdd(checkedAdd(frontStage, backStage),
|
||||
checkedMultiply(totalTimes - 1, stagePipe)),
|
||||
target.matrixPeriodNs);
|
||||
return target.getMatrixComputeLatencyNs(inputBitwidth);
|
||||
}
|
||||
|
||||
Cost getWvmmCost(Type inputType, Type outputType) const {
|
||||
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
#include "PeriodicDependencies.hpp"
|
||||
|
||||
#include <limits>
|
||||
|
||||
namespace onnx_mlir::spatial {
|
||||
|
||||
mlir::FailureOr<PeriodicDependencyEstimate> analyzePeriodicDependencies(
|
||||
size_t nodeCount, llvm::ArrayRef<PeriodicDependency> edges,
|
||||
std::string &error) {
|
||||
std::vector<std::vector<size_t>> outgoing(nodeCount);
|
||||
std::vector<size_t> indegree(nodeCount), recurrent;
|
||||
Cost upper = 0;
|
||||
for (auto [index, edge] : llvm::enumerate(edges)) {
|
||||
if (edge.source >= nodeCount || edge.target >= nodeCount) {
|
||||
error = "periodic dependency references an invalid event";
|
||||
return mlir::failure();
|
||||
}
|
||||
if (edge.delayNs > std::numeric_limits<Cost>::max() - upper) {
|
||||
error = "periodic delay sum exceeds the timing range";
|
||||
return mlir::failure();
|
||||
}
|
||||
upper += edge.delayNs;
|
||||
if (edge.distance) {
|
||||
recurrent.push_back(index);
|
||||
} else {
|
||||
outgoing[edge.source].push_back(index);
|
||||
++indegree[edge.target];
|
||||
}
|
||||
}
|
||||
std::vector<size_t> order;
|
||||
for (size_t node = 0; node < nodeCount; ++node)
|
||||
if (!indegree[node])
|
||||
order.push_back(node);
|
||||
for (size_t cursor = 0; cursor < order.size(); ++cursor)
|
||||
for (size_t index : outgoing[order[cursor]])
|
||||
if (!--indegree[edges[index].target])
|
||||
order.push_back(edges[index].target);
|
||||
if (order.size() != nodeCount) {
|
||||
error = "periodic distance-zero dependencies contain a cycle";
|
||||
return mlir::failure();
|
||||
}
|
||||
|
||||
PeriodicDependencyEstimate result;
|
||||
std::vector<Cost> span(nodeCount);
|
||||
for (size_t node : order) {
|
||||
result.withinGenerationSpanNs =
|
||||
std::max(result.withinGenerationSpanNs, span[node]);
|
||||
for (size_t index : outgoing[node]) {
|
||||
const auto &edge = edges[index];
|
||||
span[edge.target] = std::max(span[edge.target],
|
||||
checkedAdd(span[node], edge.delayNs));
|
||||
}
|
||||
}
|
||||
if (recurrent.empty() || !upper)
|
||||
return result;
|
||||
|
||||
const size_t absent = std::numeric_limits<size_t>::max();
|
||||
std::vector<double> potential(nodeCount);
|
||||
std::vector<size_t> predecessor(nodeCount, absent);
|
||||
auto infeasible = [&](double interval) {
|
||||
std::fill(potential.begin(), potential.end(), 0);
|
||||
std::fill(predecessor.begin(), predecessor.end(), absent);
|
||||
auto relax = [&](size_t index) {
|
||||
const auto &edge = edges[index];
|
||||
double value = potential[edge.source] + edge.delayNs
|
||||
- interval * edge.distance;
|
||||
if (value <= potential[edge.target] + 1e-7)
|
||||
return false;
|
||||
potential[edge.target] = value;
|
||||
predecessor[edge.target] = index;
|
||||
return true;
|
||||
};
|
||||
for (size_t node : order)
|
||||
for (size_t index : outgoing[node])
|
||||
relax(index);
|
||||
// Eliminate distance-zero paths by a DAG sweep. A simple residual path
|
||||
// visits at most R recurrent edges, so R+1 rounds detect a positive cycle.
|
||||
for (size_t round = 0; round <= recurrent.size(); ++round) {
|
||||
++result.relaxationRounds;
|
||||
bool changed = false;
|
||||
for (size_t index : recurrent)
|
||||
changed |= relax(index);
|
||||
for (size_t node : order)
|
||||
for (size_t index : outgoing[node])
|
||||
changed |= relax(index);
|
||||
if (!changed)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
result.recurrenceUpperNs = upper;
|
||||
for (unsigned iteration = 0;
|
||||
iteration < 64 && result.recurrenceUpperNs - result.recurrenceLowerNs > 1;
|
||||
++iteration) {
|
||||
double middle = (result.recurrenceLowerNs + result.recurrenceUpperNs) / 2;
|
||||
if (middle == result.recurrenceLowerNs || middle == result.recurrenceUpperNs)
|
||||
break;
|
||||
if (infeasible(middle))
|
||||
result.recurrenceLowerNs = middle;
|
||||
else
|
||||
result.recurrenceUpperNs = middle;
|
||||
}
|
||||
if (result.recurrenceUpperNs - result.recurrenceLowerNs > 1) {
|
||||
error = "periodic timing exceeds one-nanosecond floating-point precision";
|
||||
return mlir::failure();
|
||||
}
|
||||
if (!infeasible(result.recurrenceLowerNs))
|
||||
return result;
|
||||
|
||||
// Recover witness cycles from the last longest-path predecessor forest.
|
||||
std::vector<size_t> seen(nodeCount, absent);
|
||||
double best = 0;
|
||||
for (size_t start = 0; start < nodeCount; ++start) {
|
||||
size_t node = start;
|
||||
while (seen[node] == absent && predecessor[node] != absent) {
|
||||
seen[node] = start;
|
||||
node = edges[predecessor[node]].source;
|
||||
}
|
||||
if (seen[node] != start || predecessor[node] == absent)
|
||||
continue;
|
||||
size_t first = node;
|
||||
Cost delay = 0, distance = 0;
|
||||
std::vector<size_t> cycle;
|
||||
do {
|
||||
size_t index = predecessor[node];
|
||||
cycle.push_back(index);
|
||||
delay = checkedAdd(delay, edges[index].delayNs);
|
||||
distance = checkedAdd(distance, static_cast<Cost>(edges[index].distance));
|
||||
node = edges[index].source;
|
||||
} while (node != first);
|
||||
double ratio = distance ? static_cast<double>(delay) / distance : 0;
|
||||
if (ratio > best) {
|
||||
best = ratio;
|
||||
std::reverse(cycle.begin(), cycle.end());
|
||||
result.criticalCycle = std::move(cycle);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace onnx_mlir::spatial
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
|
||||
#include "Utils.hpp"
|
||||
#include "mlir/Support/LogicalResult.h"
|
||||
#include "llvm/ADT/ArrayRef.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace onnx_mlir::spatial {
|
||||
|
||||
// t(target, k) >= t(source, k - distance) + delayNs.
|
||||
struct PeriodicDependency {
|
||||
size_t source = 0;
|
||||
size_t target = 0;
|
||||
Cost delayNs = 0;
|
||||
unsigned distance = 0;
|
||||
};
|
||||
|
||||
struct PeriodicDependencyEstimate {
|
||||
double recurrenceLowerNs = 0;
|
||||
double recurrenceUpperNs = 0;
|
||||
Cost withinGenerationSpanNs = 0;
|
||||
std::vector<size_t> criticalCycle;
|
||||
size_t relaxationRounds = 0;
|
||||
};
|
||||
|
||||
// Requires an acyclic distance-zero graph. Brackets the maximum cycle ratio
|
||||
// within one nanosecond; storage is linear, without generation unrolling.
|
||||
mlir::FailureOr<PeriodicDependencyEstimate> analyzePeriodicDependencies(
|
||||
size_t nodeCount, llvm::ArrayRef<PeriodicDependency> edges,
|
||||
std::string &error);
|
||||
|
||||
} // namespace onnx_mlir::spatial
|
||||
+67
-13
@@ -1,6 +1,7 @@
|
||||
#include "llvm/ADT/DenseMap.h"
|
||||
#include "llvm/ADT/SmallBitVector.h"
|
||||
#include "llvm/ADT/STLExtras.h"
|
||||
#include "llvm/Support/raw_ostream.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
@@ -1079,10 +1080,20 @@ static LogicalResult packPipelineAssignment(const ComputeGraph &graph,
|
||||
}
|
||||
|
||||
|
||||
struct PipelineCandidateCapture {
|
||||
bool enabled = false;
|
||||
std::vector<MergeScheduleResult> packed;
|
||||
|
||||
void consider(const MergeScheduleResult &candidate) {
|
||||
if (enabled)
|
||||
packed.push_back(candidate);
|
||||
}
|
||||
};
|
||||
|
||||
static LogicalResult assignPipelineCores(const ComputeGraph &graph,
|
||||
MergeScheduleResult &schedule, size_t pipelineStages,
|
||||
const SchedulingTarget &physicalTarget, std::string &error, bool memoryAware,
|
||||
bool sharePublications = true) {
|
||||
bool sharePublications = true, PipelineCandidateCapture *capture = nullptr) {
|
||||
PipelineCoreLayout balancedLayout(physicalTarget.processorCount, pipelineStages);
|
||||
if (!balancedLayout.isValid()) {
|
||||
error = "pipeline scheduling received an incompatible physical core layout";
|
||||
@@ -1098,6 +1109,8 @@ static LogicalResult assignPipelineCores(const ComputeGraph &graph,
|
||||
if (failed(packPipelineAssignment(graph, taskModel, assignment, candidate,
|
||||
pipelineStages, physicalTarget, error)))
|
||||
continue;
|
||||
if (capture)
|
||||
capture->consider(candidate);
|
||||
auto maximumStageSpan = [](const MergeScheduleResult &result) {
|
||||
return result.costs.stageSpanNs.empty() ? Cost{0}
|
||||
: *llvm::max_element(result.costs.stageSpanNs);
|
||||
@@ -1162,27 +1175,68 @@ mlir::LogicalResult runPipelineScheduler(const ComputeGraph& graph,
|
||||
MergeScheduleResult& schedule,
|
||||
size_t pipelineStages,
|
||||
const SchedulingTarget& physicalTarget,
|
||||
std::string& error) {
|
||||
std::string& error,
|
||||
std::vector<MergeScheduleResult> *candidates) {
|
||||
PipelineCoreLayout pipelineLayout(
|
||||
physicalTarget.processorCount, pipelineStages);
|
||||
if (pipelineStages <= 1 || !pipelineLayout.isValid()) {
|
||||
error = "pipeline scheduling requires a valid balanced physical core layout";
|
||||
return mlir::failure();
|
||||
}
|
||||
if (failed(assignPipelineCores(graph, schedule, pipelineStages, physicalTarget, error, false, false)))
|
||||
PipelineCandidateCapture capture{candidates != nullptr, {}};
|
||||
if (failed(assignPipelineCores(graph, schedule, pipelineStages, physicalTarget, error, false, false, &capture)))
|
||||
return failure();
|
||||
if (!physicalTarget.sharedMemoryWidthBytes || graph.publicationTransfers.empty())
|
||||
return success();
|
||||
std::string candidateError;
|
||||
// Retain the calibrated phase-1 winner before evaluating sharing-aware cuts.
|
||||
(void)assignPipelineCores(graph, schedule, pipelineStages, physicalTarget, candidateError, true, false);
|
||||
std::vector<size_t> taskStages;
|
||||
for (const auto &node : graph.nodes)
|
||||
taskStages.push_back(schedule.processorStages[
|
||||
schedule.computeToCpuMap.lookup(node.instance)]);
|
||||
schedule.costs.boundaryMemory = getPipelineBoundaryMemoryDemand(
|
||||
graph, taskStages, physicalTarget);
|
||||
(void)assignPipelineCores(graph, schedule, pipelineStages, physicalTarget, candidateError, true, true);
|
||||
if (physicalTarget.sharedMemoryWidthBytes && !graph.publicationTransfers.empty()) {
|
||||
(void)assignPipelineCores(graph, schedule, pipelineStages, physicalTarget, candidateError, true, false, &capture);
|
||||
std::vector<size_t> taskStages;
|
||||
for (const auto &node : graph.nodes)
|
||||
taskStages.push_back(schedule.processorStages[
|
||||
schedule.computeToCpuMap.lookup(node.instance)]);
|
||||
schedule.costs.boundaryMemory = getPipelineBoundaryMemoryDemand(
|
||||
graph, taskStages, physicalTarget);
|
||||
(void)assignPipelineCores(graph, schedule, pipelineStages, physicalTarget, candidateError, true, true, &capture);
|
||||
}
|
||||
if (candidates) {
|
||||
auto activeStages = [&](const MergeScheduleResult &result) {
|
||||
llvm::SmallBitVector stages(pipelineStages);
|
||||
for (const auto &node : graph.nodes)
|
||||
stages.set(result.processorStages[result.computeToCpuMap.lookup(node.instance)]);
|
||||
return stages;
|
||||
};
|
||||
auto samePlacement = [&](const MergeScheduleResult &a, const MergeScheduleResult &b) {
|
||||
for (const auto &node : graph.nodes) {
|
||||
size_t cpu = a.computeToCpuMap.lookup(node.instance);
|
||||
if (cpu != b.computeToCpuMap.lookup(node.instance)
|
||||
|| a.computeToCpuSlotMap.lookup(node.instance) != b.computeToCpuSlotMap.lookup(node.instance)
|
||||
|| a.processorStages[cpu] != b.processorStages[cpu])
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
auto originalStages = activeStages(schedule);
|
||||
SmallVector<size_t> alternatives;
|
||||
for (auto [index, candidate] : llvm::enumerate(capture.packed)) {
|
||||
if (activeStages(candidate) != originalStages || samePlacement(candidate, schedule))
|
||||
continue;
|
||||
if (llvm::none_of(alternatives, [&](size_t other) {
|
||||
return samePlacement(candidate, capture.packed[other]);
|
||||
}))
|
||||
alternatives.push_back(index);
|
||||
}
|
||||
candidates->push_back(schedule);
|
||||
for (size_t index : alternatives) {
|
||||
auto &candidate = capture.packed[index];
|
||||
std::vector<size_t> taskStages;
|
||||
for (const auto &node : graph.nodes)
|
||||
taskStages.push_back(candidate.processorStages[
|
||||
candidate.computeToCpuMap.lookup(node.instance)]);
|
||||
candidate.costs.boundaryMemory = getPipelineBoundaryMemoryDemand(
|
||||
graph, taskStages, physicalTarget);
|
||||
candidates->push_back(std::move(candidate));
|
||||
}
|
||||
}
|
||||
return success();
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -124,7 +124,8 @@ mlir::LogicalResult runPipelineScheduler(const ComputeGraph& graph,
|
||||
MergeScheduleResult& schedule,
|
||||
size_t pipelineStages,
|
||||
const SchedulingTarget& physicalTarget,
|
||||
std::string& error);
|
||||
std::string& error,
|
||||
std::vector<MergeScheduleResult> *candidates = nullptr);
|
||||
|
||||
enum class PipelineWorkloadPreparation {
|
||||
Ready,
|
||||
|
||||
+30
@@ -1,10 +1,40 @@
|
||||
#include "ScheduleEvaluation.hpp"
|
||||
#include "MergeSchedule.hpp"
|
||||
|
||||
#include <cmath>
|
||||
#include <queue>
|
||||
|
||||
namespace onnx_mlir::spatial {
|
||||
|
||||
bool WholeScheduleCost::eligible() const {
|
||||
return primary && alternative && std::isfinite(*primary) && std::isfinite(*alternative)
|
||||
&& *primary > 0 && *alternative > 0 && relativeUncertainty
|
||||
&& std::isfinite(*relativeUncertainty) && *relativeUncertainty >= 0
|
||||
&& *relativeUncertainty < 1;
|
||||
}
|
||||
|
||||
size_t selectPipelineCandidate(llvm::ArrayRef<WholeScheduleCost> scores, std::string &reason) {
|
||||
if (scores.empty() || !scores.front().eligible()) {
|
||||
reason = "original estimate unavailable";
|
||||
return 0;
|
||||
}
|
||||
size_t best = 0;
|
||||
auto upper = [&](size_t i) {
|
||||
return std::max(*scores[i].primary, *scores[i].alternative)
|
||||
/ (1 - *scores[i].relativeUncertainty);
|
||||
};
|
||||
for (size_t i = 1; i < scores.size(); ++i)
|
||||
if (scores[i].eligible() && upper(i) < upper(best)) best = i;
|
||||
if (!best) { reason = "original has the lowest conservative estimate"; return 0; }
|
||||
double originalLower = std::min(*scores.front().primary, *scores.front().alternative);
|
||||
if (upper(best) >= originalLower / (1 + *scores.front().relativeUncertainty)) {
|
||||
reason = "candidate and original overlap static prediction uncertainty";
|
||||
return 0;
|
||||
}
|
||||
reason = "candidate improves on original under both arbitration tie policies and prediction uncertainty";
|
||||
return best;
|
||||
}
|
||||
|
||||
void recordScheduleCosts(const ScheduleEvaluation &evaluation,
|
||||
MergeScheduleResult &schedule) {
|
||||
schedule.costs.totalWorkNs = evaluation.totalWork;
|
||||
|
||||
+3
@@ -9,6 +9,9 @@ namespace onnx_mlir::spatial {
|
||||
|
||||
struct MergeScheduleResult;
|
||||
|
||||
size_t selectPipelineCandidate(llvm::ArrayRef<WholeScheduleCost> scores,
|
||||
std::string &reason);
|
||||
|
||||
struct ScheduleEvaluation {
|
||||
std::vector<Time> taskStarts;
|
||||
std::vector<Time> taskEnds;
|
||||
|
||||
+73
@@ -2,10 +2,18 @@
|
||||
|
||||
#include <cassert>
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "mlir/Support/LogicalResult.h"
|
||||
|
||||
#include "Utils.hpp"
|
||||
|
||||
namespace mlir { class ModuleOp; }
|
||||
namespace llvm::json { class Object; }
|
||||
|
||||
namespace onnx_mlir {
|
||||
namespace spatial {
|
||||
|
||||
@@ -26,6 +34,25 @@ struct SharedMemoryDemand {
|
||||
}
|
||||
};
|
||||
|
||||
struct ComputeGraph;
|
||||
struct ScheduledComputeMaterializationResult;
|
||||
struct DeferredTransferPlan;
|
||||
struct DeferredBoundaryPlan;
|
||||
|
||||
struct WholeScheduleCost {
|
||||
// Steady-state intervals in nanoseconds. The alternative tests sensitivity.
|
||||
std::optional<double> primary, alternative;
|
||||
std::string reason;
|
||||
std::string identity;
|
||||
std::optional<double> relativeUncertainty;
|
||||
bool eligible() const;
|
||||
};
|
||||
|
||||
struct ScheduleCostQuery {
|
||||
std::string identity;
|
||||
std::function<WholeScheduleCost(llvm::json::Object &)> evaluate;
|
||||
};
|
||||
|
||||
struct SchedulingTarget {
|
||||
size_t processorCount = 0;
|
||||
size_t residentWeightCapacity = 0;
|
||||
@@ -35,6 +62,7 @@ struct SchedulingTarget {
|
||||
Cost computeBitwidth = 8;
|
||||
Cost processorPeriodNs = 1;
|
||||
Cost localMemoryWidthBytes = 64;
|
||||
Cost localMemoryPeriodNs = 1;
|
||||
Cost localMemoryReadLatencyCycles = 1;
|
||||
Cost localMemoryWriteLatencyCycles = 1;
|
||||
Cost transferWidthBytes = 8;
|
||||
@@ -48,6 +76,22 @@ struct SchedulingTarget {
|
||||
Cost sharedMemoryWriteLatencyNs = 0;
|
||||
bool zeroSplatUsesSharedMemory = true;
|
||||
|
||||
// Input is a verified, target-lowered candidate. Preparation and evaluation
|
||||
// are read-only. An absent query keeps the original schedule.
|
||||
std::function<mlir::FailureOr<ScheduleCostQuery>(mlir::ModuleOp,
|
||||
llvm::json::Object &)> prepareScheduleCost;
|
||||
std::string wholeScheduleCostUnavailable;
|
||||
std::function<void(const ComputeGraph &,
|
||||
const ScheduledComputeMaterializationResult &, const DeferredTransferPlan &,
|
||||
const DeferredBoundaryPlan &)> reportPeriodicSchedule;
|
||||
|
||||
Cost getLocalMemoryServiceNs(Cost bytes, bool write) const {
|
||||
Cost accesses = bytes / localMemoryWidthBytes
|
||||
+ (bytes % localMemoryWidthBytes != 0);
|
||||
return checkedMultiply(accesses, checkedMultiply(localMemoryPeriodNs,
|
||||
write ? localMemoryWriteLatencyCycles : localMemoryReadLatencyCycles));
|
||||
}
|
||||
|
||||
SharedMemoryDemand getSharedMemoryDemand(
|
||||
Cost bytesPerRequest, Cost requests, bool write) const {
|
||||
SharedMemoryDemand demand;
|
||||
@@ -83,6 +127,35 @@ struct SchedulingTarget {
|
||||
Cost matrixInputBufferLatencyCycles = 0;
|
||||
bool matrixPipeline = true;
|
||||
|
||||
Cost getMatrixComputeLatencyNs(Cost inputBitwidth) const {
|
||||
auto divideRoundedUp = [](Cost value, Cost width) {
|
||||
return value / width + (value % width != 0);
|
||||
};
|
||||
Cost inputTimes = divideRoundedUp(inputBitwidth, matrixInputResolutionBits);
|
||||
Cost inputPasses = divideRoundedUp(matrixRows, matrixInputParallelism);
|
||||
Cost outputPasses = divideRoundedUp(matrixColumns, matrixOutputParallelism);
|
||||
Cost readCycles = divideRoundedUp(matrixReadLatencyNs, matrixPeriodNs);
|
||||
Cost frontStage = matrixInputBufferLatencyCycles + matrixInputLatencyCycles
|
||||
+ readCycles + matrixSampleLatencyCycles;
|
||||
Cost backPipe = std::max(matrixOutputLatencyCycles,
|
||||
checkedAdd(matrixShiftLatencyCycles,
|
||||
matrixBufferLatencyCycles));
|
||||
Cost backStage = checkedAdd(
|
||||
checkedAdd(matrixOutputLatencyCycles, matrixShiftLatencyCycles),
|
||||
matrixBufferLatencyCycles);
|
||||
backStage = checkedAdd(backStage, checkedMultiply(outputPasses - 1, backPipe));
|
||||
Cost totalTimes = checkedMultiply(inputTimes, inputPasses);
|
||||
if (!matrixPipeline)
|
||||
return checkedMultiply(
|
||||
checkedMultiply(checkedAdd(frontStage, backStage), totalTimes),
|
||||
matrixPeriodNs);
|
||||
Cost stagePipe = std::max(frontStage, backStage);
|
||||
return checkedMultiply(
|
||||
checkedAdd(checkedAdd(frontStage, backStage),
|
||||
checkedMultiply(totalTimes - 1, stagePipe)),
|
||||
matrixPeriodNs);
|
||||
}
|
||||
|
||||
Cost getInterProcessorLatencyNs(size_t source,
|
||||
size_t destination) const {
|
||||
assert(source < processorCount && destination < processorCount
|
||||
|
||||
@@ -17,7 +17,7 @@ std::unique_ptr<mlir::Pass> createScheduleAndRealizeSpatialPass();
|
||||
std::unique_ptr<mlir::Pass> createScheduleAndRealizeSpatialPass(
|
||||
const SchedulingTarget& target,
|
||||
SpatialDataflowExportStage exportStage,
|
||||
size_t pipelineStages = 1);
|
||||
size_t pipelineStages = 1, bool periodicDiagnostics = false);
|
||||
}
|
||||
|
||||
std::unique_ptr<mlir::Pass> createONNXToSpatialPass();
|
||||
|
||||
Reference in New Issue
Block a user