469 lines
20 KiB
C++
469 lines
20 KiB
C++
#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
|