better throughput scheduling
Validate Operations / validate-operations (push) Failing after 3h13m5s

update results_comparison.csv
This commit is contained in:
NiccoloN
2026-10-19 22:11:51 +02:00
parent 034c197260
commit 48e9fb3795
21 changed files with 1636 additions and 259 deletions
+16
View File
@@ -82,6 +82,10 @@ spatial::SchedulingTarget getDefaultPimSchedulingTarget() {
target.matrixInputReadMultiplier = 8;
target.matrixColumns = crossbarSize.getValue();
target.synchronizationRegisterCount = kPimEventRegisterCount;
target.sharedMemoryWidthBytes = 16;
target.sharedMemoryReadLatencyNs = 8;
target.sharedMemoryWriteLatencyNs = 10;
target.zeroSplatUsesSharedMemory = false;
setDefaultPimInterProcessorLatencies(target);
return target;
@@ -266,6 +270,18 @@ spatial::SchedulingTarget getPimSchedulingTarget() {
requireObject(core, "local_memory_config", "chip_config.core_config");
const llvm::json::Object& network =
requireObject(chip, "network_config", "chip_config");
// Older target configurations omit global memory and use adapter defaults.
if (chip.get("global_memory_config")) {
const llvm::json::Object& sharedMemory =
requireObject(chip, "global_memory_config", "chip_config");
Cost memoryPeriod = getConfigCost(sharedMemory, "period", Cost{1});
target.sharedMemoryWidthBytes = getConfigCost(
sharedMemory, "data_width", target.sharedMemoryWidthBytes);
target.sharedMemoryReadLatencyNs = checkedMultiply(memoryPeriod,
getConfigCost(sharedMemory, "read_latency_cycle", Cost{8}, true));
target.sharedMemoryWriteLatencyNs = checkedMultiply(memoryPeriod,
getConfigCost(sharedMemory, "write_latency_cycle", Cost{10}, true));
}
std::optional<int64_t> coreCount = chip.getInteger("core_cnt");
if (!coreCount || *coreCount <= 0)
@@ -514,6 +514,20 @@ FailureOr<DeferredBoundaryPlan> buildDeferredBoundaryPlan(
DenseMap<BoundaryKey, unsigned> indices;
DenseMap<DeferredExchangePlan *, unsigned> resultSteps;
DenseMap<RequirementFamily *, LaneSet> coverage;
DenseMap<int64_t, unsigned> publicationSteps;
DenseMap<ExternalTransferFamily *, SmallVector<int64_t>> storeFlags;
DenseSet<int64_t> storedPublications;
for (const ScheduledTransferSlice &slice : schedule.slices) {
ExternalTransferFamily &family = *slice.family;
if (!family.hostRouted)
continue;
storeFlags.try_emplace(&family, family.targetCores.size(), 0);
for (size_t offset = 0; offset < slice.transferCount; ++offset) {
int64_t slot = family.hostOffsets.valueAt(slice.familyOffset + offset);
auto [entry, inserted] = publicationSteps.try_emplace(slot, slice.sourceInsertionStep);
entry->second = std::min(entry->second, slice.sourceInsertionStep);
}
}
for (const std::unique_ptr<DeferredExchangePlan> &exchange :
transfers.exchanges) {
@@ -537,10 +551,23 @@ FailureOr<DeferredBoundaryPlan> buildDeferredBoundaryPlan(
for (const ScheduledTransferSlice &slice : schedule.slices) {
ExternalTransferFamily &family = *slice.family;
BoundaryProgram &source = getBoundary(
boundaries, indices,
{family.sourceScheduled, slice.sourceInsertionStep});
appendSend(source, slice);
if (!family.hostRouted) {
BoundaryProgram &source = getBoundary(boundaries, indices,
{family.sourceScheduled, slice.sourceInsertionStep});
appendSend(source, slice);
} else {
// Notify every reader at the first existing publication boundary. This
// also puts all reader lifetimes before the shared slot's reuse wait.
for (size_t offset = 0; offset < slice.transferCount; ++offset) {
size_t index = slice.familyOffset + offset;
int64_t slot = family.hostOffsets.valueAt(index);
BoundaryProgram &source = getBoundary(boundaries, indices,
{family.sourceScheduled, publicationSteps.lookup(slot)});
appendSend(source, {&family, index, 1,
publicationSteps.lookup(slot), slice.targetInsertionStep});
storeFlags[&family][index] = storedPublications.insert(slot).second;
}
}
BoundaryProgram &target = getBoundary(
boundaries, indices,
{family.targetScheduled, slice.targetInsertionStep});
@@ -557,6 +584,8 @@ FailureOr<DeferredBoundaryPlan> buildDeferredBoundaryPlan(
coverage)))
return failure();
}
for (auto &[family, flags] : storeFlags)
family->hostStoreFlags = StaticIntSequence::fromValues(flags);
for (const std::unique_ptr<DeferredExchangePlan> &exchange :
transfers.exchanges) {
@@ -22,6 +22,7 @@ struct LogicalTransferMetadataView {
StaticIntSequenceChain sourceCores;
StaticIntSequenceChain targetCores;
StaticIntSequenceChain hostOffsets;
StaticIntSequenceChain hostStoreFlags;
StaticIntSequenceChain eventRegisters;
StaticIntSequenceChain waitValues;
StaticIntSequenceChain targetLanes;
@@ -115,6 +116,7 @@ static void appendMetadata(const ScheduledTransferSlice &slice, LogicalTransferM
metadata.targetCores.append(family.targetCores, familyIndex, count);
if (family.hostRouted) {
metadata.hostOffsets.append(family.hostOffsets, familyIndex, count);
metadata.hostStoreFlags.append(family.hostStoreFlags, familyIndex, count);
metadata.eventRegisters.append(
family.eventRegisters, familyIndex, count);
metadata.waitValues.append(family.waitValues, familyIndex, count);
@@ -225,6 +227,7 @@ static LogicalResult emitSendRun(const EmitSendRun &run, Value lane, unsigned la
return failure();
std::optional<StaticIntGrid> hostOffsets;
std::optional<StaticIntGrid> eventRegisters;
std::optional<StaticIntGrid> storeFlags;
if (firstFamily.hostRouted) {
auto offsets = buildGrid(
&LogicalTransferMetadataView::hostOffsets,
@@ -232,10 +235,12 @@ static LogicalResult emitSendRun(const EmitSendRun &run, Value lane, unsigned la
auto events = buildGrid(
&LogicalTransferMetadataView::eventRegisters,
logical.eventRegisters.valueAt(0));
if (failed(offsets) || failed(events))
auto flags = buildGrid(&LogicalTransferMetadataView::hostStoreFlags, 0);
if (failed(offsets) || failed(events) || failed(flags))
return failure();
hostOffsets = std::move(*offsets);
eventRegisters = std::move(*events);
storeFlags = std::move(*flags);
}
GridGeometry projectionGrids;
for (auto [geometryIndex, sourceMember] : llvm::enumerate(metadataGeometryMembers)) {
@@ -265,29 +270,47 @@ static LogicalResult emitSendRun(const EmitSendRun &run, Value lane, unsigned la
auto emitOne = [&](Value action, Value runtimeLane) -> LogicalResult {
Value localOffset = localOffsets->emitLookup(action, runtimeLane, anchor, context.constants, context.rewriter, loc);
MixedSliceGeometry projection = lookupGeometry(projectionGrids, action, runtimeLane, anchor, context, loc);
auto payload = materializeSendPayload(requirement, localOffset, projectionGrids[0].empty() ? nullptr : &projection, context, loc);
if (failed(payload))
return failure();
Value sourceCore = transferGrids->sourceCores().emitLookup(
action, runtimeLane, anchor, context.constants, context.rewriter, loc);
Value targetCore = transferGrids->targetCores().emitLookup(
action, runtimeLane, anchor, context.constants, context.rewriter, loc);
Operation *send;
if (firstFamily.hostRouted)
send = SpatHostStoreSyncOp::create(
if (firstFamily.hostRouted) {
Value flag = storeFlags->emitLookup(action, runtimeLane, anchor,
context.constants, context.rewriter, loc);
Value condition = arith::CmpIOp::create(context.rewriter, loc,
arith::CmpIPredicate::ne, flag, context.constants.getIndex(0));
auto conditional = scf::IfOp::create(context.rewriter, loc,
TypeRange{}, condition, true);
OpBuilder::InsertionGuard guard(context.rewriter);
context.rewriter.setInsertionPoint(conditional.thenYield());
auto payload = materializeSendPayload(requirement, localOffset,
projectionGrids[0].empty() ? nullptr : &projection, context, loc);
if (failed(payload))
return failure();
auto send = SpatHostStoreSyncOp::create(
context.rewriter, loc, sourceCore, targetCore,
hostOffsets->emitLookup(
action, runtimeLane, anchor, context.constants, context.rewriter, loc),
eventRegisters->emitLookup(
action, runtimeLane, anchor, context.constants, context.rewriter, loc),
*payload);
else
send = SpatChannelSendOp::create(
setLogicalTransferMetadata(send, logical);
context.rewriter.setInsertionPoint(conditional.elseYield());
SpatSyncOp::create(context.rewriter, loc, targetCore,
eventRegisters->emitLookup(action, runtimeLane, anchor,
context.constants, context.rewriter, loc));
} else {
auto payload = materializeSendPayload(requirement, localOffset,
projectionGrids[0].empty() ? nullptr : &projection, context, loc);
if (failed(payload))
return failure();
auto send = SpatChannelSendOp::create(
context.rewriter, loc,
transferGrids->channels().emitLookup(
action, runtimeLane, anchor, context.constants, context.rewriter, loc),
sourceCore, targetCore, *payload);
setLogicalTransferMetadata(send, logical);
setLogicalTransferMetadata(send, logical);
}
return success();
};
Value runtimeLane = lane ? lane : context.constants.getIndex(0);
@@ -235,6 +235,7 @@ struct ExternalTransferFamily {
StaticIntSequence targetCores = StaticIntSequence::uniform(0, 1);
StaticIntSequence channelIds = StaticIntSequence::uniform(0, 1);
StaticIntSequence hostOffsets = StaticIntSequence::uniform(0, 1);
StaticIntSequence hostStoreFlags = StaticIntSequence::uniform(1, 1);
StaticIntSequence eventRegisters = StaticIntSequence::uniform(0, 1);
StaticIntSequence waitValues = StaticIntSequence::uniform(1, 1);
bool hostRouted = false;
@@ -4,6 +4,7 @@
#include "DeferredProjectionAnalysis.hpp"
#include "DeferredTransferPlanning.hpp"
#include "HostPublicationIdentity.hpp"
#include "src/Accelerators/PIM/Common/PimCommon.hpp"
#include "src/Accelerators/PIM/Common/Support/CheckedArithmetic.hpp"
@@ -361,30 +362,6 @@ static LogicalResult buildAvailabilityFamilies(
family.targetCores = StaticIntSequence::fromValues(targetCores);
family.channelIds = StaticIntSequence::affine(nextChannel, 1, count);
family.hostRouted = runAvailability == Availability::Host;
if (family.hostRouted) {
auto fragmentType = dyn_cast<ShapedType>(
requirement.publicationFragmentType);
auto fragmentBytes = fragmentType
? pim::getCheckedShapedTypeSizeInBytes(
fragmentType, exchange.deferred,
"pipeline host transfer fragment")
: FailureOr<uint64_t>(failure());
if (failed(fragmentBytes))
return failure();
auto bytes = pim::checkedMul<size_t>(
count, static_cast<size_t>(*fragmentBytes), exchange.deferred,
"pipeline host transfer storage");
if (failed(bytes))
return failure();
family.hostOffsets = StaticIntSequence::affine(
plan.pipelineHostBufferBytes, *fragmentBytes, count);
auto endOffset = pim::checkedAdd<size_t>(
plan.pipelineHostBufferBytes, *bytes, exchange.deferred,
"pipeline host transfer storage");
if (failed(endOffset))
return failure();
plan.pipelineHostBufferBytes = *endOffset;
}
nextChannel += count;
exchange.externalTransferCount += count;
exchange.external.push_back(std::move(family));
@@ -450,6 +427,48 @@ static LogicalResult buildExchanges(func::FuncOp funcOp, DeferredTransferPlan& p
return success();
}
static LogicalResult allocateHostPublications(DeferredTransferPlan &plan) {
DenseMap<HostPublicationIdentity, int64_t> offsets;
for (auto &exchange : plan.exchanges)
for (ExternalTransferFamily &family : exchange->external) {
if (!family.hostRouted)
continue;
RequirementFamily &requirement = *family.requirement;
auto type = dyn_cast<ShapedType>(requirement.publicationFragmentType);
auto bytes = type ? pim::getCheckedShapedTypeSizeInBytes(
type, exchange->deferred, "pipeline host transfer fragment")
: FailureOr<uint64_t>(failure());
if (failed(bytes))
return failure();
SmallVector<int64_t> hostOffsets;
unsigned begin = family.targetLanes.intervals().front().begin;
unsigned requirementBegin = requirement.targetLanes.intervals().front().begin;
for (size_t index = 0; index < family.targetCores.size(); ++index) {
int64_t fragment = requirement.producerLocalOffsets
? requirement.producerLocalOffsets->valueAt(begin + index - requirementBegin) : 0;
auto identity = getHostPublicationIdentity(requirement.producer,
fragment, requirement.publicationFragmentType,
!requirement.producerProjection);
auto found = identity ? offsets.find(*identity) : offsets.end();
if (found != offsets.end()) {
hostOffsets.push_back(found->second);
continue;
}
hostOffsets.push_back(plan.pipelineHostBufferBytes);
if (identity)
offsets.try_emplace(*identity, plan.pipelineHostBufferBytes);
auto end = pim::checkedAdd<size_t>(plan.pipelineHostBufferBytes, *bytes,
exchange->deferred, "pipeline host transfer storage");
if (failed(end))
return failure();
plan.pipelineHostBufferBytes = *end;
}
family.hostOffsets = StaticIntSequence::fromValues(hostOffsets);
family.hostStoreFlags = StaticIntSequence::uniform(1, hostOffsets.size());
}
return success();
}
static LogicalResult
retargetBlueprint(DeferredTransferPlan& plan, SpatBlueprintOp blueprint, GraphBatchPublicationCache& publicationCache) {
if (!isFragmentAssembly(blueprint.getMode()))
@@ -528,7 +547,8 @@ FailureOr<DeferredTransferPlan> buildDeferredTransferPlan(
if (failed(collectScheduledOperations(
materialization, plan, pipelineStages, processorCount))
|| failed(collectProducedValues(materialization, plan))
|| failed(buildExchanges(funcOp, plan)))
|| failed(buildExchanges(funcOp, plan))
|| failed(allocateHostPublications(plan)))
return failure();
return std::move(plan);
}
@@ -0,0 +1,24 @@
#pragma once
#include "mlir/IR/Types.h"
#include "llvm/ADT/DenseMapInfo.h"
#include <optional>
#include <tuple>
namespace onnx_mlir::spatial {
// The owner identifies one immutable result generation. Fragment indices are
// physical source slots, never logical reconstruction coordinates.
using HostPublicationIdentity = std::tuple<const void *, int64_t, mlir::Type>;
inline std::optional<HostPublicationIdentity> getHostPublicationIdentity(
const void *owner, int64_t fragment, mlir::Type payloadType,
bool completeFragment) {
// shortcut: scalar projections stay separate; share them when both analyses
// can represent their exact source geometry.
if (!completeFragment)
return std::nullopt;
return HostPublicationIdentity{owner, fragment, payloadType};
}
} // namespace onnx_mlir::spatial
@@ -124,6 +124,15 @@ void dumpScheduledComputeReport(ModuleOp moduleOp, func::FuncOp funcOp, const Me
for (auto [stage, demand] : llvm::enumerate(costs.stageSerialDemandNs))
os << " estimated stage " << stage << " maximum core compute/incident-transfer demand (ns): "
<< demand << "\n";
if (costs.baselineMemory.readRequests || costs.boundaryMemory.readRequests) {
auto printMemory = [&](StringRef name, const SharedMemoryDemand &demand) {
os << " estimated " << name << " shared memory: read_bytes=" << demand.readBytes
<< " write_bytes=" << demand.writeBytes << " read_requests=" << demand.readRequests
<< " write_requests=" << demand.writeRequests << " service_ns=" << demand.serviceNs << "\n";
};
printMemory("baseline", costs.baselineMemory);
printMemory("boundary", costs.boundaryMemory);
}
llvm::MapVector<size_t, SmallVector<size_t>> stageCores;
for (auto [core, stage] : llvm::enumerate(schedule.processorStages))
stageCores[stage].push_back(core);
@@ -17,6 +17,7 @@
#include "llvm/Support/Casting.h"
#include <algorithm>
#include <functional>
#include <iterator>
#include <limits>
#include <optional>
@@ -297,18 +298,22 @@ Cost getOperationCost(Operation& op, const SchedulerCostModel& costModel) {
return checkedAdd(SchedulerCostModel::kFallbackOperationCost, nestedCost);
}
static Cost getPositiveStepTripCount(int64_t lower, int64_t upper, int64_t step) {
assert(step > 0);
if (upper <= lower)
return 0;
Cost distance = static_cast<Cost>(upper) - static_cast<Cost>(lower);
Cost stride = static_cast<Cost>(step);
return distance / stride + (distance % stride != 0);
}
std::optional<uint64_t> getStaticTripCount(scf::ForOp loop) {
auto lb = getConstantIntValue(loop.getLowerBound());
auto ub = getConstantIntValue(loop.getUpperBound());
auto step = getConstantIntValue(loop.getStep());
if (!lb || !ub || !step || *step <= 0)
return std::nullopt;
if (*ub <= *lb)
return 0;
uint64_t distance = static_cast<uint64_t>(*ub - *lb);
uint64_t stride = static_cast<uint64_t>(*step);
return (distance + stride - 1) / stride;
return getPositiveStepTripCount(*lb, *ub, *step);
}
Cost getComputeBodyCost(Region& body, const SchedulerCostModel& costModel) {
@@ -410,20 +415,23 @@ static FailureOr<bool>
collectProjectedEdges(SpatComputeBatch producer, Value input,
const ComputeInstance& consumerInstance,
size_t processorCount, size_t targetIndex,
const ComputeGraph& graph,
ComputeGraph& graph,
const SchedulerCostModel& costModel,
GraphBatchPublicationCache& publicationCache,
SmallVectorImpl<ComputeGraphEdge>& rawEdges) {
auto consumer = dyn_cast<SpatComputeBatch>(consumerInstance.op);
if (!consumer)
auto inputs = consumer ? consumer.getInputs()
: cast<SpatCompute>(consumerInstance.op).getInputs();
auto inputIt = llvm::find(inputs, input);
if (inputIt == inputs.end())
return false;
auto inputIt = llvm::find(consumer.getInputs(), input);
if (inputIt == consumer.getInputs().end())
size_t inputIndex = std::distance(inputs.begin(), inputIt);
auto inputArg = consumer ? consumer.getInputArgument(inputIndex)
: cast<SpatCompute>(consumerInstance.op).getInputArgument(inputIndex);
if (consumer && !consumer.getLaneArgument())
return false;
size_t inputIndex = std::distance(consumer.getInputs().begin(), inputIt);
std::optional<BlockArgument> inputArg = consumer.getInputArgument(inputIndex);
std::optional<BlockArgument> laneArg = consumer.getLaneArgument();
if (!inputArg || !laneArg)
Value laneArg = consumer ? Value(*consumer.getLaneArgument()) : Value();
if (!inputArg)
return false;
auto publication = getGraphBatchPublicationMap(
producer, cast<OpResult>(input).getResultNumber(), publicationCache);
@@ -431,61 +439,227 @@ collectProjectedEdges(SpatComputeBatch producer, Value input,
return failure();
SmallVector<ComputeGraphEdge, 4> edges;
SmallVector<PublicationTransfer> publications;
DenseMap<std::pair<Value, int64_t>, size_t> publicationIndices;
llvm::SmallBitVector selectedSlots(producer.getLaneCount());
Cost fragmentBytes = costModel.getByteSize((*publication)->publicationFragmentType,
costModel.getComputeBitwidth((*publication)->publicationFragmentType));
TransferCost fragmentCost = costModel.getTransferCostFromBytes(
costModel.getByteSize((*publication)->publicationFragmentType,
costModel.getComputeBitwidth((*publication)->publicationFragmentType)));
bool exactDependencies = static_cast<bool>(consumer);
DenseMap<Value, int64_t> bindings;
for (Operation* user : inputArg->getUsers()) {
auto extract = dyn_cast<tensor::ExtractSliceOp>(user);
if (!extract || extract.getSource() != *inputArg || extract.getMixedOffsets().empty()
|| extract.getMixedSizes().empty() || extract.getMixedStrides().empty())
return false;
SmallVector<scf::ForOp> loops;
for (Operation *parent = extract->getParentOp(); parent != consumerInstance.op;
parent = parent->getParentOp()) {
auto loop = dyn_cast<scf::ForOp>(parent);
if (!loop) return false;
loops.push_back(loop);
}
std::reverse(loops.begin(), loops.end());
for (uint32_t lane = consumerInstance.laneStart;
lane < consumerInstance.laneStart + consumerInstance.laneCount;
++lane) {
FailureOr<int64_t> offset =
evaluateIndexLike(extract.getMixedOffsets().front(), bindings, lane, *laneArg);
FailureOr<int64_t> size =
evaluateIndexLike(extract.getMixedSizes().front(), bindings, lane, *laneArg);
FailureOr<int64_t> stride =
evaluateIndexLike(extract.getMixedStrides().front(), bindings, lane, *laneArg);
if (failed(offset) || failed(size) || failed(stride) || *offset < 0 || *size <= 0 || *stride <= 0)
return false;
for (int64_t index = 0; index < *size; ++index) {
int64_t slot = *offset + index * *stride;
if (slot < 0 || slot >= producer.getLaneCount())
lane < consumerInstance.laneStart + consumerInstance.laneCount; ++lane) {
auto recordProjection = [&](bool dependency, Cost repetitions = 1) {
auto offset = evaluateIndexLike(extract.getMixedOffsets().front(), bindings, lane, laneArg);
auto size = evaluateIndexLike(extract.getMixedSizes().front(), bindings, lane, laneArg);
auto stride = evaluateIndexLike(extract.getMixedStrides().front(), bindings, lane, laneArg);
if (failed(offset) || failed(size) || failed(stride) || *offset < 0 || *size <= 0 || *stride <= 0)
return false;
if (selectedSlots.test(slot))
continue;
selectedSlots.set(slot);
int64_t producerLane = (*publication)->physicalSlotToGraphLane[slot];
ComputeInstance instance = getBatchChunkForLane(
producer, static_cast<uint32_t>(producerLane), processorCount);
auto source = graph.instanceToIndex.find(instance);
if (source == graph.instanceToIndex.end())
return producer.emitOpError("projected producer has no compute instance"), failure();
edges.push_back({source->second, targetIndex, fragmentCost});
if (*offset >= producer.getLaneCount()
|| *size > 1 + (producer.getLaneCount() - 1 - *offset) / *stride)
return false;
for (int64_t index = 0; index < *size; ++index) {
int64_t slot = *offset + index * *stride;
if (slot < 0 || slot >= producer.getLaneCount()) return false;
int64_t producerLane = (*publication)->physicalSlotToGraphLane[slot];
ComputeInstance instance = getBatchChunkForLane(producer, producerLane, processorCount);
auto source = graph.instanceToIndex.find(instance);
if (source == graph.instanceToIndex.end()) return false;
if (!dependency) {
auto [entry, inserted] = publicationIndices.try_emplace(
std::make_pair(extract.getResult(), producerLane), publications.size());
if (inserted)
publications.push_back({source->second, targetIndex, input,
producerLane, extract.getResult(), fragmentBytes, repetitions,
(*publication)->publicationFragmentType});
else
publications[entry->second].count = checkedAdd(
publications[entry->second].count, repetitions);
} else if (!selectedSlots.test(slot)) {
selectedSlots.set(slot);
edges.push_back({source->second, targetIndex, fragmentCost});
}
}
return true;
};
if (consumer && !recordProjection(true)) exactDependencies = false;
// Repeated invariant projections need one demand with a multiplicity.
Cost repetitions = 1;
bool invariantBounds = true;
for (scf::ForOp loop : loops) {
auto lower = evaluateIndexLike(loop.getLowerBound(), bindings, lane, laneArg);
auto upper = evaluateIndexLike(loop.getUpperBound(), bindings, lane, laneArg);
auto step = evaluateIndexLike(loop.getStep(), bindings, lane, laneArg);
if (failed(lower) || failed(upper) || failed(step) || *step <= 0) {
invariantBounds = false;
break;
}
Cost trips = getPositiveStepTripCount(*lower, *upper, *step);
repetitions = checkedMultiply(repetitions, trips);
}
if (invariantBounds && (repetitions == 0 || recordProjection(false, repetitions)))
continue;
std::function<bool(size_t)> visit = [&](size_t depth) {
if (depth < loops.size()) {
auto loop = loops[depth];
auto lower = evaluateIndexLike(loop.getLowerBound(), bindings, lane, laneArg);
auto upper = evaluateIndexLike(loop.getUpperBound(), bindings, lane, laneArg);
auto step = evaluateIndexLike(loop.getStep(), bindings, lane, laneArg);
if (failed(lower) || failed(upper) || failed(step) || *step <= 0) return false;
int64_t iv = *lower;
for (Cost remaining = getPositiveStepTripCount(*lower, *upper, *step);
remaining; --remaining) {
bindings[loop.getInductionVar()] = iv;
if (!visit(depth + 1)) return false;
if (remaining > 1) iv += *step;
}
bindings.erase(loop.getInductionVar());
return true;
}
return recordProjection(false);
};
if (!visit(0)) return false;
}
}
llvm::append_range(rawEdges, edges);
// Memory accounting can resolve loop projections without changing the
// conservative dependency edges used by latency PEFT.
if (exactDependencies)
llvm::append_range(rawEdges, edges);
llvm::append_range(graph.publicationTransfers, publications);
return exactDependencies;
}
struct InputFragment {
Type type;
Cost count;
Value projection;
};
static bool isSharedMemoryInput(Value input, const SchedulingTarget &target) {
if (isa<BlockArgument>(input))
return true;
Attribute value;
if (!matchPattern(input, m_Constant(&value)) || !isa<ElementsAttr>(value))
return false;
auto dense = dyn_cast<DenseElementsAttr>(value);
if (!target.zeroSplatUsesSharedMemory && dense && dense.isSplat()) {
auto element = dense.getSplatValue<Attribute>();
if (auto floating = dyn_cast<FloatAttr>(element))
return !floating.getValue().isZero() || floating.getValue().isNegative();
if (auto integer = dyn_cast<IntegerAttr>(element))
return !integer.getValue().isZero();
}
return true;
}
std::optional<TransferCost> getProjectedInputTransferCost(
Value input, const ComputeInstance& instance,
const SchedulerCostModel& costModel) {
static std::pair<Cost, Cost> getProjectionMemoryRequests(Type type, Value projection,
const SchedulerCostModel &costModel) {
Cost bytes = costModel.getByteSize(type, costModel.getComputeBitwidth(type));
Cost requests = 1;
if (auto extract = projection.getDefiningOp<tensor::ExtractSliceOp>();
extract && extract.getSourceType().hasStaticShape()
&& !ShapedType::isDynamicShape(extract.getStaticSizes())
&& !ShapedType::isDynamicShape(extract.getStaticStrides())) {
auto strides = computeRowMajorStrides(extract.getSourceType().getShape());
Cost run = 1;
for (size_t dim = strides.size(); dim-- > 0;) {
Cost size = extract.getStaticSizes()[dim];
if (size == 1) continue;
if (checkedMultiply(static_cast<Cost>(strides[dim]),
static_cast<Cost>(extract.getStaticStrides()[dim])) != run)
break;
run = checkedMultiply(run, size);
}
Cost elements = cast<ShapedType>(type).getNumElements();
if (elements) {
requests = checkedMultiply(requests, elements / run);
bytes = SchedulerCostModel::ceilDiv(
checkedMultiply(run, costModel.getComputeBitwidth(type)), Cost{8});
}
}
return {bytes, requests};
}
static SharedMemoryDemand getInputMemoryDemand(const InputFragment &fragment,
const SchedulerCostModel &costModel) {
auto [bytes, runs] = getProjectionMemoryRequests(fragment.type, fragment.projection, costModel);
return costModel.target.getSharedMemoryDemand(bytes,
checkedMultiply(runs, fragment.count), false);
}
static SharedMemoryDemand getCapturedConstantMemoryDemand(
Operation *owner, const SchedulerCostModel &costModel) {
// shortcut: later aliasing/load folding can change baseline requests; exact
// accounting requires a placed, bufferized program.
SharedMemoryDemand demand;
owner->walk([&](Operation *user) {
if (user == owner) return;
for (Value value : user->getOperands()) {
if (isa<BlockArgument>(value) || !isSharedMemoryInput(value, costModel.target)) continue;
if (auto extract = dyn_cast<tensor::ExtractOp>(user)) {
DenseMap<Value, int64_t> bindings;
for (Operation *parent = user->getParentOp(); parent != owner;
parent = parent->getParentOp())
if (auto loop = dyn_cast<scf::ForOp>(parent))
if (auto lower = getConstantIntValue(loop.getLowerBound()))
bindings[loop.getInductionVar()] = *lower;
auto batch = dyn_cast<SpatComputeBatch>(owner);
Value lane = batch && batch.getLaneArgument() ? Value(*batch.getLaneArgument()) : Value();
if (succeeded(evaluateIndexLike(extract.getResult(), bindings, 0, lane)))
continue;
}
if (auto vmm = dyn_cast<SpatVMMOp>(user); vmm && vmm.getWeight() == value) continue;
if (auto extract = dyn_cast<tensor::ExtractSliceOp>(user)) {
if (llvm::all_of(extract.getResult().getUses(), [&](OpOperand &use) {
auto vmm = dyn_cast<SpatVMMOp>(use.getOwner());
return vmm && vmm.getWeight() == extract.getResult();
})) continue;
}
Cost count = 1;
for (Operation *parent = user->getParentOp(); parent != owner;
parent = parent->getParentOp()) {
if (auto loop = dyn_cast<scf::ForOp>(parent)) {
auto trips = getStaticTripCount(loop);
if (trips) count = checkedMultiply(count, static_cast<Cost>(*trips));
}
}
auto extract = dyn_cast<tensor::ExtractSliceOp>(user);
Type type = extract ? extract.getResult().getType() : value.getType();
demand += getInputMemoryDemand({type, count, extract ? extract.getResult() : value}, costModel);
}
});
return demand;
}
std::optional<SmallVector<InputFragment>> getProjectedInputFragments(
Value input, const ComputeInstance &instance) {
auto batch = dyn_cast<SpatComputeBatch>(instance.op);
if (!batch)
auto inputs = batch ? batch.getInputs()
: cast<SpatCompute>(instance.op).getInputs();
auto found = llvm::find(inputs, input);
if (found == inputs.end())
return std::nullopt;
auto found = llvm::find(batch.getInputs(), input);
if (found == batch.getInputs().end())
return std::nullopt;
auto argument = batch.getInputArgument(found - batch.getInputs().begin());
size_t index = found - inputs.begin();
auto argument = batch ? batch.getInputArgument(index)
: cast<SpatCompute>(instance.op).getInputArgument(index);
if (!argument)
return std::nullopt;
TransferCost cost;
SmallVector<InputFragment> fragments;
for (Operation* user : argument->getUsers()) {
auto extract = dyn_cast<tensor::ExtractSliceOp>(user);
if (!extract || extract.getSource() != *argument)
@@ -499,12 +673,26 @@ std::optional<TransferCost> getProjectedInputTransferCost(
return std::nullopt;
count = checkedMultiply(count, static_cast<Cost>(*trips));
}
auto type = extract.getResult().getType();
fragments.push_back({extract.getResult().getType(), count, extract.getResult()});
}
return fragments;
}
std::optional<TransferCost> getProjectedInputTransferCost(
Value input, const ComputeInstance& instance,
const SchedulerCostModel& costModel) {
if (!isa<SpatComputeBatch>(instance.op))
return std::nullopt;
auto fragments = getProjectedInputFragments(input, instance);
if (!fragments)
return std::nullopt;
TransferCost cost;
for (const InputFragment &inputFragment : *fragments) {
TransferCost fragment = costModel.getTransferCostFromBytes(
costModel.getByteSize(type, costModel.getComputeBitwidth(type)));
costModel.getByteSize(inputFragment.type, costModel.getComputeBitwidth(inputFragment.type)));
cost = addTransferCosts(cost,
{checkedMultiply(fragment.fixed, count),
checkedMultiply(fragment.networkFlits, count)});
{checkedMultiply(fragment.fixed, inputFragment.count),
checkedMultiply(fragment.networkFlits, inputFragment.count)});
}
return cost;
}
@@ -578,8 +766,12 @@ TransferCost getProducerTransferCost(Value input,
const ComputeInstance& consumerInstance, const ProducerValueRef& producerRef,
const SchedulerCostModel& costModel);
static LogicalResult collectPublicationTransfer(Value input, size_t targetIndex,
const ProducerValueRef &producer, size_t sourceIndex, ComputeGraph &graph,
const SchedulerCostModel &costModel, GraphBatchPublicationCache &cache);
LogicalResult collectBlueprintEdges(Value input, size_t targetIndex,
const ComputeGraph& graph, size_t processorCount,
ComputeGraph& graph, size_t processorCount,
const SchedulerCostModel& costModel,
GraphBatchPublicationCache& publicationCache,
SmallVectorImpl<ComputeGraphEdge>& edges) {
@@ -607,6 +799,9 @@ LogicalResult collectBlueprintEdges(Value input, size_t targetIndex,
return blueprint.emitOpError("fragment source has no compute instance");
edges.push_back({indexed->second, targetIndex,
getProducerTransferCost(source, graph.nodes[targetIndex].instance, producer, costModel)});
if (failed(collectPublicationTransfer(source, targetIndex, producer,
indexed->second, graph, costModel, publicationCache)))
return failure();
}
continue;
}
@@ -629,6 +824,9 @@ LogicalResult collectBlueprintEdges(Value input, size_t targetIndex,
elements = checkedMultiply(elements, static_cast<Cost>(size));
auto fragmentType = (*publication)->publicationFragmentType;
Cost bytes = costModel.getByteSize(fragmentType, costModel.getComputeBitwidth(fragmentType));
graph.publicationTransfers.push_back({indexed->second, targetIndex, source,
lane, input, bytes, graph.nodes[targetIndex].instance.laneCount,
fragmentType});
TransferCost transfer = costModel.getTransferCostFromBytes(bytes);
auto sourceOffsets = blueprint.getFragmentSourceOffsets();
if (!sourceOffsets)
@@ -643,6 +841,41 @@ LogicalResult collectBlueprintEdges(Value input, size_t targetIndex,
return success();
}
static LogicalResult collectPublicationTransfer(Value input, size_t targetIndex,
const ProducerValueRef &producer, size_t sourceIndex, ComputeGraph &graph,
const SchedulerCostModel &costModel, GraphBatchPublicationCache &cache) {
const ComputeInstance &consumer = graph.nodes[targetIndex].instance;
auto batch = dyn_cast<SpatComputeBatch>(producer.instance.op);
Value value = producer.instance.op->getResult(producer.resultIndex);
if (batch) {
auto publication = getGraphBatchPublicationMap(batch, producer.resultIndex, cache);
if (failed(publication))
return failure();
auto type = (*publication)->publicationFragmentType;
Cost bytes = costModel.getByteSize(type, costModel.getComputeBitwidth(type));
for (uint32_t lane = producer.instance.laneStart;
lane < producer.instance.laneStart + producer.instance.laneCount; ++lane)
graph.publicationTransfers.push_back({sourceIndex, targetIndex, value,
lane, input, bytes, consumer.laneCount, type});
return success();
}
if (auto fragments = getProjectedInputFragments(input, consumer)) {
for (const InputFragment &fragment : *fragments) {
Cost bytes = costModel.getByteSize(fragment.type, costModel.getComputeBitwidth(fragment.type));
auto [storeBytes, storeRuns] = getProjectionMemoryRequests(
fragment.type, fragment.projection, costModel);
graph.publicationTransfers.push_back({sourceIndex, targetIndex, value,
0, fragment.projection, bytes, fragment.count, {}, storeBytes, storeRuns});
}
} else {
Cost bytes = costModel.getByteSize(input.getType(), costModel.getComputeBitwidth(input.getType()));
graph.publicationTransfers.push_back({sourceIndex, targetIndex, value,
0, input, bytes, consumer.laneCount,
input == value ? value.getType() : Type()});
}
return success();
}
TransferCost getProducerTransferCost(
Value input, const ComputeInstance& consumerInstance,
const ProducerValueRef& producerRef,
@@ -846,10 +1079,35 @@ static void collectResidentWeightsFromOp(Operation* op,
if (!lb || !ub || !step || *step <= 0)
return;
for (int64_t iv = *lb; iv < *ub; iv += *step) {
ResidentWeightSet invariantWeights;
bool invariant = true, hasWeights = false;
loop.walk([&](Operation *nested) {
if (isa<scf::ForOp>(nested) && nested != loop.getOperation())
invariant = false;
auto vmm = dyn_cast<SpatVMMOp>(nested);
if (!vmm)
return;
hasWeights = true;
auto weight = getStaticResidentWeight(owner, vmm.getWeight(), bindings, lane, laneArg);
if (failed(weight))
invariant = false;
else
addResidentWeight(invariantWeights, *weight);
});
if (invariant || !hasWeights) {
if (*lb < *ub)
for (ResidentWeight &weight : invariantWeights)
addResidentWeight(usage, std::move(weight));
return;
}
int64_t iv = *lb;
for (Cost remaining = getPositiveStepTripCount(*lb, *ub, *step);
remaining; --remaining) {
bindings[loop.getInductionVar()] = iv;
for (Operation& nested : loop.getBody()->without_terminator())
collectResidentWeightsFromOp(&nested, owner, bindings, usage, laneArg, lane);
if (remaining > 1) iv += *step;
}
bindings.erase(loop.getInductionVar());
return;
@@ -1053,9 +1311,29 @@ FailureOr<ComputeGraph> buildComputeGraph(Operation* entryOp,
llvm::SmallVector<ComputeGraphEdge, 16> rawEdges;
GraphBatchPublicationCache publicationCache;
DenseMap<Operation *, SharedMemoryDemand> capturedMemory;
for (const auto& [targetIndex, node] : llvm::enumerate(graph.nodes)) {
auto [captured, inserted] = capturedMemory.try_emplace(node.instance.op);
if (inserted)
captured->second = getCapturedConstantMemoryDemand(node.instance.op, costModel);
auto memory = captured->second;
memory.readBytes = checkedMultiply(memory.readBytes, static_cast<Cost>(node.instance.laneCount));
memory.readRequests = checkedMultiply(memory.readRequests, static_cast<Cost>(node.instance.laneCount));
memory.serviceNs = checkedMultiply(memory.serviceNs, static_cast<Cost>(node.instance.laneCount));
graph.baselineMemory += memory;
llvm::SmallVector<Value, 4> inputs = getComputeInstanceInputs(node.instance);
for (Value input : inputs) {
size_t publicationsBefore = graph.publicationTransfers.size();
if (isSharedMemoryInput(input, target)) {
if (auto fragments = getProjectedInputFragments(input, node.instance)) {
for (const InputFragment &fragment : *fragments)
graph.baselineMemory += getInputMemoryDemand(fragment, costModel);
} else {
graph.baselineMemory += target.getSharedMemoryDemand(
costModel.getByteSize(input.getType(), costModel.getComputeBitwidth(input.getType())),
node.instance.laneCount, false);
}
}
if (auto producer = input.getDefiningOp<SpatComputeBatch>()) {
auto projected = collectProjectedEdges(producer, input, node.instance,
computePartitionCount, targetIndex, graph, costModel, publicationCache, rawEdges);
@@ -1074,6 +1352,7 @@ FailureOr<ComputeGraph> buildComputeGraph(Operation* entryOp,
auto producers = collectProducerValueRefs(input, computePartitionCount, publicationCache);
if (failed(producers))
return failure();
bool memoryCollected = graph.publicationTransfers.size() != publicationsBefore;
for (const ProducerValueRef& producerRef : *producers) {
auto producerIt = graph.instanceToIndex.find(producerRef.instance);
if (producerIt == graph.instanceToIndex.end())
@@ -1081,10 +1360,21 @@ FailureOr<ComputeGraph> buildComputeGraph(Operation* entryOp,
rawEdges.push_back({producerIt->second,
targetIndex,
getProducerTransferCost(input, node.instance, producerRef, costModel)});
if (!memoryCollected && failed(collectPublicationTransfer(input, targetIndex, producerRef,
producerIt->second, graph, costModel, publicationCache)))
return failure();
}
}
}
for (Region &region : entryOp->getRegions())
for (Block &block : region)
if (block.getTerminator()->hasTrait<OpTrait::ReturnLike>())
for (Value output : block.getTerminator()->getOperands())
graph.baselineMemory += target.getSharedMemoryDemand(
costModel.getByteSize(output.getType(), costModel.getComputeBitwidth(output.getType())),
1, true);
std::vector<ComputeGraphEdge> aggregatedEdges = aggregateEdges(rawEdges);
graph.edges.insert(graph.edges.end(), aggregatedEdges.begin(), aggregatedEdges.end());
graph.successors.assign(graph.nodes.size(), {});
@@ -1097,6 +1387,24 @@ FailureOr<ComputeGraph> buildComputeGraph(Operation* entryOp,
return graph;
}
SharedMemoryDemand getPipelineBoundaryMemoryDemand(const ComputeGraph &graph,
ArrayRef<size_t> taskStages, const SchedulingTarget &target,
bool sharePublications) {
assert(taskStages.size() == graph.nodes.size());
SharedMemoryDemand demand;
llvm::DenseSet<HostPublicationIdentity> stored;
for (const PublicationTransfer &transfer : graph.publicationTransfers)
if (taskStages[transfer.source] != taskStages[transfer.target]) {
demand += target.getSharedMemoryDemand(transfer.bytes, transfer.count, false);
auto identity = sharePublications ? transfer.sharedIdentity() : std::nullopt;
if (!identity || stored.insert(*identity).second)
demand += sharePublications
? transfer.getStoreMemoryDemand(target, identity ? 1 : transfer.count)
: target.getSharedMemoryDemand(transfer.bytes, transfer.count, true);
}
return demand;
}
bool verifyAcyclic(const ComputeGraph& graph) {
std::vector<size_t> remainingParents(graph.nodes.size(), 0);
std::queue<size_t> readyNodes;
@@ -1,4 +1,5 @@
#pragma once
#include "../HostPublicationIdentity.hpp"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Value.h"
@@ -63,14 +64,45 @@ struct ComputeGraphEdge {
TransferCost transferCost;
};
// One physical fragment demand, before routing.
struct PublicationTransfer {
size_t source = 0;
size_t target = 0;
mlir::Value publication;
int64_t graphLane = 0;
mlir::Value projection;
Cost bytes = 0;
Cost count = 1;
mlir::Type completeFragmentType = {};
Cost storeRunBytes = 0;
Cost storeRuns = 1;
std::optional<HostPublicationIdentity> sharedIdentity() const {
return getHostPublicationIdentity(publication.getAsOpaquePointer(),
graphLane, completeFragmentType, static_cast<bool>(completeFragmentType));
}
SharedMemoryDemand getStoreMemoryDemand(const SchedulingTarget &target,
Cost publications) const {
return target.getSharedMemoryDemand(storeRunBytes ? storeRunBytes : bytes,
checkedMultiply(publications, storeRuns), true);
}
};
struct ComputeGraph {
std::vector<ComputeGraphNode> nodes;
std::vector<ComputeGraphEdge> edges;
std::vector<std::vector<std::pair<size_t, TransferCost>>> successors;
std::vector<std::vector<std::pair<size_t, TransferCost>>> predecessors;
llvm::DenseMap<ComputeInstance, size_t> instanceToIndex;
std::vector<PublicationTransfer> publicationTransfers;
SharedMemoryDemand baselineMemory;
};
SharedMemoryDemand getPipelineBoundaryMemoryDemand(const ComputeGraph &graph,
llvm::ArrayRef<size_t> taskStages, const SchedulingTarget &target,
bool sharePublications = true);
mlir::FailureOr<ComputeGraph> buildComputeGraph(mlir::Operation* entryOp,
const SchedulingTarget& target,
size_t computePartitionCount = 0);
@@ -8,6 +8,7 @@
#include <vector>
#include "ComputeInstance.hpp"
#include "SchedulingTarget.hpp"
namespace onnx_mlir {
namespace spatial {
@@ -20,6 +21,8 @@ struct ScheduleCostSummary {
uint64_t completionNs = 0;
std::vector<uint64_t> stageSpanNs;
std::vector<uint64_t> stageSerialDemandNs;
SharedMemoryDemand baselineMemory;
SharedMemoryDemand boundaryMemory;
};
struct MergeScheduleResult {
@@ -28,7 +28,9 @@ using TaskCosts = std::vector<Cost>;
using namespace mlir;
struct PipelineTaskModel {
PipelineTaskModel(const ComputeGraph &graph, const SchedulingTarget &target) : weights(graph) {
PipelineTaskModel(const ComputeGraph &graph, const SchedulingTarget &target,
bool sharePublications = true)
: weights(graph), graph(graph), target(target), sharePublications(sharePublications) {
llvm::DenseMap<Operation *, Cost> transposeAdjustments;
schedulingCosts.reserve(graph.nodes.size());
executionCosts.reserve(graph.nodes.size());
@@ -52,6 +54,9 @@ struct PipelineTaskModel {
TaskCosts schedulingCosts;
TaskCosts executionCosts;
IndexedResidentWeights weights;
const ComputeGraph &graph;
const SchedulingTarget &target;
bool sharePublications;
};
static Cost estimateOrderedPackCost(
@@ -189,6 +194,7 @@ struct PipelineGroupModel {
std::vector<size_t> taskToGroup;
TaskList groupOrder;
TaskCosts groupCosts;
TaskCosts groupExecutionCosts;
size_t minimumStageZeroEnd = 0;
std::vector<size_t> furthestSuccessorBefore;
bool hasCrossingEdge = false;
@@ -281,15 +287,22 @@ static FailureOr<PipelineGroupModel> buildPipelineGroups(
}
TaskCosts groupCosts(groups.size());
TaskCosts groupExecutionCosts(groups.size());
TaskCosts internalEnds(graph.nodes.size());
TaskCosts executionEnds(graph.nodes.size());
for (size_t group : groupOrder)
for (size_t task : groups[group].tasks) {
Cost start = 0;
Cost executionStart = 0;
for (const auto &[predecessor, transferCost] : graph.predecessors[task])
if (taskToGroup[predecessor] == group)
if (taskToGroup[predecessor] == group) {
start = std::max(start, internalEnds[predecessor]);
executionStart = std::max(executionStart, executionEnds[predecessor]);
}
internalEnds[task] = checkedAdd(start, model.schedulingCosts[task]);
groupCosts[group] = std::max(groupCosts[group], internalEnds[task]);
executionEnds[task] = checkedAdd(executionStart, model.executionCosts[task]);
groupExecutionCosts[group] = std::max(groupExecutionCosts[group], executionEnds[task]);
}
std::vector<size_t> position(groups.size());
@@ -316,136 +329,259 @@ static FailureOr<PipelineGroupModel> buildPipelineGroups(
}
return PipelineGroupModel{std::move(groups), std::move(taskToGroup),
std::move(groupOrder), std::move(groupCosts), minimumStageZeroEnd,
std::move(groupOrder), std::move(groupCosts), std::move(groupExecutionCosts), minimumStageZeroEnd,
std::move(furthestSuccessorBefore), hasCrossingEdge};
}
static FailureOr<std::vector<size_t>> partitionPipelineGroups(
struct PipelinePartitionCandidate {
Cost priority = 0;
Cost execution = 0;
Cost memory = 0;
size_t start = 0;
size_t parent = 0;
};
using PartitionFrontier = SmallVector<PipelinePartitionCandidate, 8>;
static void retainPartitionCandidates(PartitionFrontier &frontier,
PipelinePartitionCandidate candidate, Cost baselineMemory, bool memoryAware) {
if (!memoryAware) {
if (frontier.empty() || candidate.priority < frontier.front().priority)
frontier.assign(1, candidate);
return;
}
frontier.push_back(candidate);
size_t legacy = 0;
for (size_t i = 1; i < frontier.size(); ++i)
if (frontier[i].priority < frontier[legacy].priority)
legacy = i;
PartitionFrontier kept;
for (size_t i = 0; i < frontier.size(); ++i) {
bool dominated = false;
for (size_t j = 0; j < frontier.size() && i != legacy; ++j)
if (i != j && frontier[j].execution <= frontier[i].execution
&& frontier[j].memory <= frontier[i].memory
&& (frontier[j].execution < frontier[i].execution
|| frontier[j].memory < frontier[i].memory || j < i)) {
dominated = true;
break;
}
if (!dominated)
kept.push_back(frontier[i]);
}
// Bound the frontier, preserving the legacy path and both resource extremes.
constexpr size_t limit = 8;
if (kept.size() > limit) {
llvm::stable_sort(kept, [](const auto &a, const auto &b) {
return std::tie(a.execution, a.memory, a.priority)
< std::tie(b.execution, b.memory, b.priority);
});
auto score = [&](const auto &a) {
return std::make_tuple(std::max(a.execution, checkedAdd(baselineMemory, a.memory)),
a.execution, a.memory, a.priority);
};
size_t best = 0, lowestPriority = 0, lowestMemory = 0;
for (size_t i = 1; i < kept.size(); ++i) {
if (score(kept[i]) < score(kept[best])) best = i;
if (kept[i].priority < kept[lowestPriority].priority) lowestPriority = i;
if (kept[i].memory < kept[lowestMemory].memory) lowestMemory = i;
}
SmallVector<size_t> indices;
auto add = [&](size_t i) {
if (!llvm::is_contained(indices, i) && indices.size() < limit)
indices.push_back(i);
};
for (size_t i : {size_t{0}, lowestMemory, lowestPriority, best}) add(i);
for (size_t i = 0; i < limit; ++i) add(i * (kept.size() - 1) / (limit - 1));
for (size_t i = 0; i < kept.size(); ++i) add(i);
frontier.clear();
for (size_t i : indices) frontier.push_back(kept[i]);
} else {
frontier = std::move(kept);
}
}
static TaskCosts getPipelineCutMemoryCosts(const PipelineGroupModel &groups,
const PipelineTaskModel &model) {
size_t count = groups.groups.size();
std::vector<size_t> position(count);
for (auto [index, group] : llvm::enumerate(groups.groupOrder)) position[group] = index;
TaskCosts starts(count + 2), ends(count + 2), costs(count + 1);
struct PublicationRange { size_t source, target; Cost service; };
llvm::DenseMap<HostPublicationIdentity, PublicationRange> publications;
for (const PublicationTransfer &transfer : model.graph.publicationTransfers) {
size_t source = position[groups.taskToGroup[transfer.source]];
size_t target = position[groups.taskToGroup[transfer.target]];
if (source == target) continue;
assert(source < target);
Cost cost = model.target.getSharedMemoryDemand(
transfer.bytes, transfer.count, false).serviceNs;
if (auto identity = model.sharePublications ? transfer.sharedIdentity() : std::nullopt) {
auto [entry, inserted] = publications.try_emplace(*identity,
PublicationRange{source, target,
transfer.getStoreMemoryDemand(model.target, 1).serviceNs});
entry->second.target = std::max(entry->second.target, target);
} else {
cost = checkedAdd(cost, model.sharePublications
? transfer.getStoreMemoryDemand(model.target, transfer.count).serviceNs
: model.target.getSharedMemoryDemand(transfer.bytes, transfer.count, true).serviceNs);
}
starts[source + 1] = checkedAdd(starts[source + 1], cost);
ends[target + 1] = checkedAdd(ends[target + 1], cost);
}
for (const auto &[identity, range] : publications) {
starts[range.source + 1] = checkedAdd(starts[range.source + 1], range.service);
ends[range.target + 1] = checkedAdd(ends[range.target + 1], range.service);
}
Cost active = 0;
for (size_t cut = 0; cut <= count; ++cut) {
active = checkedAdd(active, starts[cut]);
assert(active >= ends[cut]);
active -= ends[cut];
costs[cut] = active;
}
return costs;
}
static FailureOr<std::vector<std::vector<size_t>>> partitionPipelineGroups(
const PipelineGroupModel &constraints, const PipelineTaskModel &model,
ArrayRef<size_t> coreCounts, size_t residentWeightCapacity,
std::string &error) {
std::string &error, bool memoryAware) {
const auto &groups = constraints.groups;
const auto &groupOrder = constraints.groupOrder;
const auto &groupCosts = constraints.groupCosts;
const auto &taskWeightIds = model.weights.taskWeightIds;
size_t minimumStageZeroEnd = constraints.minimumStageZeroEnd;
const auto &furthestSuccessorBefore = constraints.furthestSuccessorBefore;
bool hasCrossingEdge = constraints.hasCrossingEdge;
size_t count = groups.size();
const Cost infinity = std::numeric_limits<Cost>::max();
const size_t noCut = std::numeric_limits<size_t>::max();
std::vector<std::vector<Cost>> best(
coreCounts.size() + 1,
std::vector<Cost>(groups.size() + 1, infinity));
std::vector<std::vector<size_t>> parent(
coreCounts.size() + 1,
std::vector<size_t>(groups.size() + 1, noCut));
std::vector<std::vector<PartitionFrontier>> best(coreCounts.size() + 1,
std::vector<PartitionFrontier>(count + 1));
using SegmentCost = std::pair<Cost, Cost>;
std::vector<size_t> stageCostCache(coreCounts.size());
std::vector<size_t> cachedCoreCounts;
std::vector<std::vector<std::vector<Cost>>> segmentCostCaches;
std::vector<std::vector<std::vector<SegmentCost>>> caches;
for (auto [stage, coreCount] : llvm::enumerate(coreCounts)) {
auto cached = llvm::find(cachedCoreCounts, coreCount);
if (cached == cachedCoreCounts.end()) {
stageCostCache[stage] = segmentCostCaches.size();
stageCostCache[stage] = caches.size();
cachedCoreCounts.push_back(coreCount);
segmentCostCaches.emplace_back(
groups.size() + 1,
std::vector<Cost>(groups.size() + 1, infinity));
caches.emplace_back(count + 1, std::vector<SegmentCost>(count + 1, {infinity, infinity}));
} else {
stageCostCache[stage] = cached - cachedCoreCounts.begin();
}
}
best[0][0] = 0;
// ponytail: operation groups are small; replace this quadratic partition
// only if scheduling profiles show it matters.
TaskCosts cutMemory = getPipelineCutMemoryCosts(constraints, model);
Cost baselineMemory = model.graph.baselineMemory.serviceNs;
best[0][0].push_back({});
for (size_t stage = 0; stage < coreCounts.size(); ++stage) {
size_t coreCount = coreCounts[stage];
size_t stageWeightCapacity = checkedMultiply(
coreCount, residentWeightCapacity);
for (size_t start = 0; start < groups.size(); ++start) {
if (best[stage][start] == infinity)
continue;
size_t capacity = checkedMultiply(coreCount, residentWeightCapacity);
for (size_t start = 0; start < count; ++start) {
if (best[stage][start].empty()) continue;
TaskList segmentTasks;
TaskCosts segmentEnds(groups.size());
Cost segmentSpan = 0;
Cost largestTask = 0;
llvm::SmallBitVector segmentWeights(model.weights.weightCount);
size_t segmentWeightCount = 0;
for (size_t end = start + 1; end <= groups.size(); ++end) {
const PipelineGroup &group = groups[groupOrder[end - 1]];
size_t groupIndex = groupOrder[end - 1];
segmentEnds[groupIndex] = checkedAdd(
segmentEnds[groupIndex], groupCosts[groupIndex]);
segmentSpan = std::max(segmentSpan, segmentEnds[groupIndex]);
largestTask = std::max(largestTask, groupCosts[groupIndex]);
for (size_t successor : group.successors)
segmentEnds[successor] = std::max(
segmentEnds[successor], segmentEnds[groupIndex]);
TaskCosts priorityEnds(count), executionEnds(count);
Cost prioritySpan = 0, executionSpan = 0, largestPriority = 0, largestExecution = 0;
llvm::SmallBitVector weights(model.weights.weightCount);
size_t weightCount = 0;
for (size_t end = start + 1; end <= count; ++end) {
size_t index = groupOrder[end - 1];
const PipelineGroup &group = groups[index];
priorityEnds[index] = checkedAdd(priorityEnds[index], constraints.groupCosts[index]);
executionEnds[index] = checkedAdd(executionEnds[index], constraints.groupExecutionCosts[index]);
prioritySpan = std::max(prioritySpan, priorityEnds[index]);
executionSpan = std::max(executionSpan, executionEnds[index]);
largestPriority = std::max(largestPriority, constraints.groupCosts[index]);
largestExecution = std::max(largestExecution, constraints.groupExecutionCosts[index]);
for (size_t successor : group.successors) {
priorityEnds[successor] = std::max(priorityEnds[successor], priorityEnds[index]);
executionEnds[successor] = std::max(executionEnds[successor], executionEnds[index]);
}
llvm::append_range(segmentTasks, group.tasks);
for (size_t weight : group.weightIds)
if (!segmentWeights.test(weight)) {
segmentWeights.set(weight);
++segmentWeightCount;
}
if (segmentWeightCount > stageWeightCapacity)
break;
if (stage == 0 && end < minimumStageZeroEnd)
continue;
if (stage != 0 && hasCrossingEdge
&& furthestSuccessorBefore[start] >= end)
continue;
Cost &segmentCost =
segmentCostCaches[stageCostCache[stage]][start][end];
if (segmentCost == infinity) {
segmentCost = estimateOrderedPackCost(
model.schedulingCosts, taskWeightIds, model.weights.weightCount,
segmentTasks, residentWeightCapacity, coreCount);
// Partition priority includes a dependency tail to avoid packing
// dependent groups onto the same cores; this is not predicted time.
segmentCost = checkedAdd(segmentCost, segmentSpan - largestTask);
}
Cost maximumLoad = std::max(best[stage][start], segmentCost);
if (maximumLoad < best[stage + 1][end]) {
best[stage + 1][end] = maximumLoad;
parent[stage + 1][end] = start;
if (!weights.test(weight)) { weights.set(weight); ++weightCount; }
if (weightCount > capacity) break;
if (stage == 0 && end < constraints.minimumStageZeroEnd) continue;
if (stage != 0 && constraints.hasCrossingEdge
&& constraints.furthestSuccessorBefore[start] >= end) continue;
auto &[priority, execution] = caches[stageCostCache[stage]][start][end];
if (priority == infinity) {
priority = checkedAdd(estimateOrderedPackCost(model.schedulingCosts,
taskWeightIds, model.weights.weightCount, segmentTasks,
residentWeightCapacity, coreCount), prioritySpan - largestPriority);
execution = memoryAware ? checkedAdd(estimateOrderedPackCost(model.executionCosts,
taskWeightIds, model.weights.weightCount, segmentTasks,
residentWeightCapacity, coreCount), executionSpan - largestExecution) : priority;
}
for (auto [parent, previous] : llvm::enumerate(best[stage][start]))
retainPartitionCandidates(best[stage + 1][end], {
std::max(previous.priority, priority), std::max(previous.execution, execution),
checkedAdd(previous.memory, cutMemory[start]), start, parent},
baselineMemory, memoryAware);
}
}
}
size_t usedStages = 0;
Cost bestLoad = infinity;
using Terminal = std::pair<size_t, size_t>;
std::vector<Terminal> terminals;
auto candidate = [&](Terminal terminal) -> const PipelinePartitionCandidate & {
return best[terminal.first][count][terminal.second];
};
auto score = [&](Terminal terminal) {
const auto &a = candidate(terminal);
return memoryAware ? std::make_tuple(std::max(a.execution, checkedAdd(baselineMemory, a.memory)),
a.execution, a.memory) : std::make_tuple(a.priority, Cost{0}, Cost{0});
};
for (size_t stages = 1; stages <= coreCounts.size(); ++stages)
if (best[stages][groups.size()] != infinity
&& best[stages][groups.size()] <= bestLoad) {
bestLoad = best[stages][groups.size()];
usedStages = stages;
}
if (usedStages == 0) {
for (size_t index = 0; index < best[stages][count].size(); ++index)
terminals.emplace_back(stages, index);
if (terminals.empty()) {
error = "pipeline scheduling cannot split operations into dependency-adjacent "
"stages within the physical crossbar limit";
return failure();
}
std::vector<size_t> groupStages(groups.size());
size_t end = groups.size();
for (size_t stage = usedStages; stage > 0; --stage) {
size_t start = parent[stage][end];
assert(start != noCut && "selected pipeline partition has no parent");
for (size_t position = start; position < end; ++position)
groupStages[groupOrder[position]] = stage - 1;
end = start;
llvm::sort(terminals, [&](Terminal a, Terminal b) {
return score(a) != score(b) ? score(a) < score(b) : a > b;
});
SmallVector<Terminal, 4> selected{terminals.front()};
auto add = [&](Terminal terminal) {
if (!llvm::is_contained(selected, terminal) && selected.size() < 4)
selected.push_back(terminal);
};
if (memoryAware) {
for (unsigned resource = 0; resource < 3; ++resource) {
auto resourceScore = [&](Terminal terminal) {
const auto &a = candidate(terminal);
return resource == 0 ? std::make_tuple(a.execution, a.memory, a.priority)
: resource == 1 ? std::make_tuple(a.memory, a.execution, a.priority)
: std::make_tuple(a.priority, a.execution, a.memory);
};
add(*llvm::min_element(terminals, [&](Terminal a, Terminal b) {
return resourceScore(a) < resourceScore(b);
}));
}
for (Terminal terminal : terminals) add(terminal);
}
return groupStages;
std::vector<std::vector<size_t>> partitions;
for (auto [stages, index] : selected) {
std::vector<size_t> groupStages(count);
size_t end = count;
for (size_t stage = stages; stage > 0; --stage) {
auto entry = best[stage][end][index];
for (size_t position = entry.start; position < end; ++position)
groupStages[groupOrder[position]] = stage - 1;
end = entry.start;
index = entry.parent;
}
if (!llvm::is_contained(partitions, groupStages))
partitions.push_back(std::move(groupStages));
}
return partitions;
}
static FailureOr<PipelineStageAssignment> assignPipelineStages(
static FailureOr<std::vector<PipelineStageAssignment>> assignPipelineStages(
const ComputeGraph &graph, const PipelineTaskModel &model,
const PipelineCoreLayout &layout, size_t residentWeightCapacity,
std::string &error) {
std::string &error, bool memoryAware) {
if (graph.nodes.empty())
return PipelineStageAssignment {
{}, std::vector<size_t>(layout.getStageSizes())};
return std::vector<PipelineStageAssignment>{{
{}, std::vector<size_t>(layout.getStageSizes())}};
auto constraints = buildPipelineGroups(graph, model, error);
if (failed(constraints))
return failure();
@@ -455,17 +591,17 @@ static FailureOr<PipelineStageAssignment> assignPipelineStages(
const auto &taskWeightIds = model.weights.taskWeightIds;
auto partitionGroups = [&](ArrayRef<size_t> coreCounts) {
return partitionPipelineGroups(*constraints, model, coreCounts,
residentWeightCapacity, error);
residentWeightCapacity, error, memoryAware);
};
FailureOr<std::vector<size_t>> initialGroupStages =
partitionGroups(layout.getStageSizes());
if (failed(initialGroupStages))
auto initialPartitions = partitionGroups(layout.getStageSizes());
if (failed(initialPartitions))
return failure();
const auto &initialGroupStages = initialPartitions->front();
std::vector<TaskList> tasksByStage(layout.getStageCount());
for (size_t group : groupOrder)
llvm::append_range(
tasksByStage[(*initialGroupStages)[group]], groups[group].tasks);
tasksByStage[initialGroupStages[group]], groups[group].tasks);
std::vector<size_t> stageSizes(layout.getStageCount(), 1);
size_t assignedCores = stageSizes.size();
for (size_t stage = 0; stage < stageSizes.size(); ++stage) {
@@ -496,7 +632,8 @@ static FailureOr<PipelineStageAssignment> assignPipelineStages(
}
TaskCosts stageDependencyTails = getPipelineStageDependencyTails(
groups, groupOrder, *initialGroupStages, constraints->groupCosts, stageSizes.size());
groups, groupOrder, initialGroupStages,
constraints->groupCosts, stageSizes.size());
auto getStageCost = [&](size_t stage, size_t coreCount) {
Cost schedulingCost = estimateOrderedPackCost(
model.schedulingCosts, taskWeightIds, model.weights.weightCount,
@@ -535,15 +672,19 @@ static FailureOr<PipelineStageAssignment> assignPipelineStages(
getStageCost(bestStage, stageSizes[bestStage] + 1);
++assignedCores;
}
FailureOr<std::vector<size_t>> refinedGroupStages =
partitionGroups(stageSizes);
if (failed(refinedGroupStages))
auto refinedPartitions = partitionGroups(stageSizes);
if (failed(refinedPartitions))
return failure();
std::vector<size_t> taskStages(graph.nodes.size());
for (size_t task = 0; task < graph.nodes.size(); ++task)
taskStages[task] = (*refinedGroupStages)[taskToGroup[task]];
return PipelineStageAssignment {
std::move(taskStages), std::move(stageSizes)};
if (memoryAware && !llvm::is_contained(*refinedPartitions, initialGroupStages))
refinedPartitions->push_back(initialGroupStages);
std::vector<PipelineStageAssignment> assignments;
for (const auto &groupStages : *refinedPartitions) {
std::vector<size_t> taskStages(graph.nodes.size());
for (size_t task = 0; task < graph.nodes.size(); ++task)
taskStages[task] = groupStages[taskToGroup[task]];
assignments.push_back({std::move(taskStages), stageSizes});
}
return assignments;
}
static bool packPipelineStage(
@@ -841,34 +982,21 @@ static LogicalResult verifyPipelineStageAssignment(
return success();
}
mlir::LogicalResult assignPipelineCores(const ComputeGraph& graph,
MergeScheduleResult& schedule,
size_t pipelineStages,
const SchedulingTarget& physicalTarget,
std::string& error) {
PipelineCoreLayout balancedLayout(
physicalTarget.processorCount, pipelineStages);
if (!balancedLayout.isValid()) {
error = "pipeline scheduling received an incompatible physical core layout";
return mlir::failure();
}
PipelineTaskModel taskModel(graph, physicalTarget);
FailureOr<PipelineStageAssignment> assignment = assignPipelineStages(
graph, taskModel, balancedLayout,
physicalTarget.residentWeightCapacity, error);
if (failed(assignment))
return failure();
static LogicalResult packPipelineAssignment(const ComputeGraph &graph,
const PipelineTaskModel &taskModel, PipelineStageAssignment assignment,
MergeScheduleResult &schedule, size_t pipelineStages,
const SchedulingTarget &physicalTarget, std::string &error) {
std::vector<TaskList> tasksByPhysicalCpu(physicalTarget.processorCount);
std::vector<size_t> searchCoreFloors(pipelineStages, 1);
std::string packingError;
bool packed = false;
for (size_t attempt = 0; attempt < physicalTarget.processorCount; ++attempt) {
PipelineCoreLayout candidateLayout(assignment->stageSizes, physicalTarget);
PipelineCoreLayout candidateLayout(assignment.stageSizes, physicalTarget);
for (TaskList &tasks : tasksByPhysicalCpu)
tasks.clear();
for (size_t task = 0; task < graph.nodes.size(); ++task) {
PipelineStageRange range =
candidateLayout.getStageRange(assignment->taskStages[task]);
candidateLayout.getStageRange(assignment.taskStages[task]);
tasksByPhysicalCpu[candidateLayout.getPhysicalCore(range.begin)].push_back(task);
}
size_t failedStage = 0;
@@ -881,26 +1009,26 @@ mlir::LogicalResult assignPipelineCores(const ComputeGraph& graph,
}
searchCoreFloors[failedStage] = std::max(
searchCoreFloors[failedStage],
assignment->stageSizes[failedStage] + 1);
assignment.stageSizes[failedStage] + 1);
std::optional<size_t> donor;
for (size_t stage = 0; stage < pipelineStages; ++stage)
if (stage != failedStage
&& assignment->stageSizes[stage]
&& assignment.stageSizes[stage]
> searchCoreFloors[stage]
&& (!donor
|| assignment->stageSizes[stage]
> assignment->stageSizes[*donor]))
|| assignment.stageSizes[stage]
> assignment.stageSizes[*donor]))
donor = stage;
if (!donor)
break;
--assignment->stageSizes[*donor];
++assignment->stageSizes[failedStage];
--assignment.stageSizes[*donor];
++assignment.stageSizes[failedStage];
}
if (!packed) {
error = packingError;
return failure();
}
PipelineCoreLayout pipelineLayout(assignment->stageSizes, physicalTarget);
PipelineCoreLayout pipelineLayout(assignment.stageSizes, physicalTarget);
auto evaluated = evaluatePipelinePlacement(
graph, taskModel, tasksByPhysicalCpu, pipelineLayout, physicalTarget, error);
if (failed(evaluated))
@@ -943,10 +1071,49 @@ mlir::LogicalResult assignPipelineCores(const ComputeGraph& graph,
recordScheduleCosts(evaluated->timing, schedule);
for (const auto &stage : evaluated->stages)
schedule.costs.stageSerialDemandNs.push_back(std::get<0>(stage));
schedule.costs.baselineMemory = graph.baselineMemory;
schedule.costs.boundaryMemory = getPipelineBoundaryMemoryDemand(
graph, assignment.taskStages, physicalTarget, taskModel.sharePublications);
populateScheduleEquivalenceClasses(graph, tasksByPhysicalCpu, schedule);
return mlir::success();
}
static LogicalResult assignPipelineCores(const ComputeGraph &graph,
MergeScheduleResult &schedule, size_t pipelineStages,
const SchedulingTarget &physicalTarget, std::string &error, bool memoryAware,
bool sharePublications = true) {
PipelineCoreLayout balancedLayout(physicalTarget.processorCount, pipelineStages);
if (!balancedLayout.isValid()) {
error = "pipeline scheduling received an incompatible physical core layout";
return failure();
}
PipelineTaskModel taskModel(graph, physicalTarget, sharePublications);
auto assignments = assignPipelineStages(graph, taskModel, balancedLayout,
physicalTarget.residentWeightCapacity, error, memoryAware);
if (failed(assignments)) return failure();
bool packed = false;
for (const auto &assignment : *assignments) {
MergeScheduleResult candidate;
if (failed(packPipelineAssignment(graph, taskModel, assignment, candidate,
pipelineStages, physicalTarget, error)))
continue;
auto maximumStageSpan = [](const MergeScheduleResult &result) {
return result.costs.stageSpanNs.empty() ? Cost{0}
: *llvm::max_element(result.costs.stageSpanNs);
};
// Store savings do not cover a longer stage when placement-dependent
// baseline loads remain approximate. Keep the calibrated phase-1 cut.
bool preservesStageSpan = !sharePublications
|| maximumStageSpan(candidate) <= maximumStageSpan(schedule);
if (!memoryAware || (preservesStageSpan
&& isBetterPipelineSchedule(candidate.costs, schedule.costs)))
schedule = std::move(candidate);
packed = true;
}
return success(packed);
}
} // namespace
PipelineCoreLayout::PipelineCoreLayout(ArrayRef<size_t> sizes,
@@ -1002,7 +1169,21 @@ mlir::LogicalResult runPipelineScheduler(const ComputeGraph& graph,
error = "pipeline scheduling requires a valid balanced physical core layout";
return mlir::failure();
}
return assignPipelineCores(graph, schedule, pipelineStages, physicalTarget, error);
if (failed(assignPipelineCores(graph, schedule, pipelineStages, physicalTarget, error, false, false)))
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);
return success();
}
} // namespace onnx_mlir::spatial
@@ -32,6 +32,26 @@ inline bool isBetterStagePlacement(const StagePlacementScore &candidate,
return candidate < current;
}
inline bool isBetterPipelineSchedule(const ScheduleCostSummary &candidate,
const ScheduleCostSummary &current) {
auto score = [](const ScheduleCostSummary &result) {
Cost stage = 0;
for (Cost span : result.stageSpanNs) stage = std::max(stage, span);
Cost memory = checkedAdd(result.baselineMemory.serviceNs, result.boundaryMemory.serviceNs);
return std::make_tuple(std::max(stage, memory), stage, memory);
};
auto currentScore = score(current);
auto candidateScore = score(candidate);
// Stage spans omit contention: do not exchange a larger compute regression
// for a smaller memory saving, even when memory remains the largest resource.
Cost currentDemand = checkedAdd(std::get<1>(currentScore), std::get<2>(currentScore));
Cost candidateDemand = checkedAdd(std::get<1>(candidateScore), std::get<2>(candidateScore));
Cost currentCoreDemand = checkedAdd(static_cast<Cost>(current.maximumCoreWorkNs), std::get<2>(currentScore));
Cost candidateCoreDemand = checkedAdd(static_cast<Cost>(candidate.maximumCoreWorkNs), std::get<2>(candidateScore));
return candidateScore < currentScore && candidateDemand <= currentDemand
&& candidateCoreDemand <= currentCoreDemand;
}
struct PipelineStageRange {
size_t begin;
size_t size;
@@ -9,6 +9,23 @@
namespace onnx_mlir {
namespace spatial {
struct SharedMemoryDemand {
Cost readBytes = 0;
Cost writeBytes = 0;
Cost readRequests = 0;
Cost writeRequests = 0;
Cost serviceNs = 0;
SharedMemoryDemand &operator+=(const SharedMemoryDemand &other) {
readBytes = checkedAdd(readBytes, other.readBytes);
writeBytes = checkedAdd(writeBytes, other.writeBytes);
readRequests = checkedAdd(readRequests, other.readRequests);
writeRequests = checkedAdd(writeRequests, other.writeRequests);
serviceNs = checkedAdd(serviceNs, other.serviceNs);
return *this;
}
};
struct SchedulingTarget {
size_t processorCount = 0;
size_t residentWeightCapacity = 0;
@@ -25,6 +42,31 @@ struct SchedulingTarget {
Cost vectorLatencyCycles = 4;
size_t synchronizationRegisterCount = 0;
// Zero width means this target has no modeled serialized memory resource.
Cost sharedMemoryWidthBytes = 0;
Cost sharedMemoryReadLatencyNs = 0;
Cost sharedMemoryWriteLatencyNs = 0;
bool zeroSplatUsesSharedMemory = true;
SharedMemoryDemand getSharedMemoryDemand(
Cost bytesPerRequest, Cost requests, bool write) const {
SharedMemoryDemand demand;
if (write) {
demand.writeBytes = checkedMultiply(bytesPerRequest, requests);
demand.writeRequests = requests;
} else {
demand.readBytes = checkedMultiply(bytesPerRequest, requests);
demand.readRequests = requests;
}
if (sharedMemoryWidthBytes) {
Cost accesses = bytesPerRequest / sharedMemoryWidthBytes
+ (bytesPerRequest % sharedMemoryWidthBytes != 0);
demand.serviceNs = checkedMultiply(requests, checkedMultiply(accesses,
write ? sharedMemoryWriteLatencyNs : sharedMemoryReadLatencyNs));
}
return demand;
}
Cost matrixRows = 128;
Cost matrixInputReadMultiplier = 1;
Cost matrixColumns = 128;