|
| 1 | +/* Copyright 2025 The MPMD Authors. |
| 2 | +
|
| 3 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +you may not use this file except in compliance with the License. |
| 5 | +You may obtain a copy of the License at |
| 6 | +
|
| 7 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +
|
| 9 | +Unless required by applicable law or agreed to in writing, software |
| 10 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +See the License for the specific language governing permissions and |
| 13 | +limitations under the License. |
| 14 | +==============================================================================*/ |
| 15 | + |
| 16 | +#include "shardy/dialect/mpmd/transforms/common/scheduler_preprocess.h" |
| 17 | + |
| 18 | +#include <algorithm> |
| 19 | +#include <cstdint> |
| 20 | + |
| 21 | +#include "mlir/Dialect/Func/IR/FuncOps.h" |
| 22 | +#include "mlir/IR/PatternMatch.h" |
| 23 | +#include "mlir/IR/Value.h" |
| 24 | +#include "mlir/Pass/PassManager.h" |
| 25 | +#include "mlir/Support/LLVM.h" |
| 26 | +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" |
| 27 | +#include "mlir/Transforms/Passes.h" |
| 28 | +#include "shardy/common/logging.h" |
| 29 | +#include "shardy/dialect/mpmd/ir/dialect.h" |
| 30 | +#include "shardy/dialect/mpmd/ir/utils.h" |
| 31 | +#include "shardy/dialect/mpmd/transforms/common/passes.h" |
| 32 | +#include "shardy/dialect/mpmd/transforms/optimize/utils.h" |
| 33 | + |
| 34 | +namespace mlir::mpmd { |
| 35 | + |
| 36 | +#define GEN_PASS_DEF_SCHEDULINGUNITVERIFIERPASS |
| 37 | +#define GEN_PASS_DEF_MOVETRANSFERSTOPRODUCERPASS |
| 38 | +#include "shardy/dialect/mpmd/transforms/common/passes.h.inc" |
| 39 | + |
| 40 | +namespace { |
| 41 | + |
| 42 | +using ::mlir::func::FuncOp; |
| 43 | + |
| 44 | +// Returns the number of microbatches in the program. |
| 45 | +// TODO(jupvfranco): This code assumes that microbatching is zero- or one- |
| 46 | +// based. Can we generalize this? |
| 47 | +uint32_t GetNumMicrobatches(FuncOp func_op) { |
| 48 | + uint32_t max_call_counter = 0; |
| 49 | + bool is_zero_based = false; |
| 50 | + func_op.walk([&max_call_counter, &is_zero_based](FragmentOp fragment) { |
| 51 | + if (auto call_counter = TryToFindCallCounter(fragment)) { |
| 52 | + if (*call_counter == 0) { |
| 53 | + is_zero_based = true; |
| 54 | + } |
| 55 | + max_call_counter = std::max(max_call_counter, *call_counter); |
| 56 | + } |
| 57 | + }); |
| 58 | + return max_call_counter + (is_zero_based ? 1 : 0); |
| 59 | +} |
| 60 | + |
| 61 | +class SchedulingUnitVerifierPass |
| 62 | + : public impl::SchedulingUnitVerifierPassBase<SchedulingUnitVerifierPass> { |
| 63 | + using SchedulingUnitVerifierPassBase::SchedulingUnitVerifierPassBase; |
| 64 | + |
| 65 | + private: |
| 66 | + void runOnFunc(FuncOp func_op) override { |
| 67 | + if (!IsMpmdFunction(func_op)) { |
| 68 | + return; |
| 69 | + } |
| 70 | + |
| 71 | + const uint32_t num_microbatches = GetNumMicrobatches(func_op); |
| 72 | + if (num_microbatches == 0) { |
| 73 | + SDY_LOG(WARNING) |
| 74 | + << "Function is not microbatched and therefore cannot be " |
| 75 | + "rescheduled."; |
| 76 | + // We exit instead of emitting an error so that this won't affect init |
| 77 | + // functions that are typically not microbatched. |
| 78 | + return; |
| 79 | + } |
| 80 | + |
| 81 | + // Check if every mesh has `num_microbatches` scheduling units, half of them |
| 82 | + // forward and the other half backward. |
| 83 | + // TODO(jupvfranco): This works for the simple schedules we support now, but |
| 84 | + // we need to revisit this logic. |
| 85 | + for (NamedMeshAttr mesh : GetSchedulableMeshes(func_op)) { |
| 86 | + int count_fwd = 0, count_bwd = 0; |
| 87 | + for (Operation& op : func_op.getOps()) { |
| 88 | + auto fragment = dyn_cast<FragmentOp>(&op); |
| 89 | + if (!fragment || !IsSchedulingUnit(fragment) || |
| 90 | + fragment.getMeshName() != mesh.getName()) { |
| 91 | + continue; |
| 92 | + } |
| 93 | + if (*TryToFindSingleTransposeCount(fragment) == 0) { |
| 94 | + count_fwd++; |
| 95 | + } else { |
| 96 | + count_bwd++; |
| 97 | + } |
| 98 | + } |
| 99 | + if (count_fwd != num_microbatches) { |
| 100 | + func_op.emitWarning("Number of forward scheduling units in mesh ") |
| 101 | + << mesh.getName() << " does not match expected number for " |
| 102 | + << num_microbatches << " microbatches. Got " << count_fwd << "."; |
| 103 | + } |
| 104 | + |
| 105 | + if (count_bwd != num_microbatches) { |
| 106 | + func_op.emitWarning("Number of backward scheduling units in mesh ") |
| 107 | + << mesh.getName() << " does not match expected number for " |
| 108 | + << num_microbatches << " microbatches. Got " << count_bwd << "."; |
| 109 | + } |
| 110 | + } |
| 111 | + } |
| 112 | +}; |
| 113 | + |
| 114 | +class MoveTransfersToProducerPass |
| 115 | + : public impl::MoveTransfersToProducerPassBase< |
| 116 | + MoveTransfersToProducerPass> { |
| 117 | + using MoveTransfersToProducerPassBase::MoveTransfersToProducerPassBase; |
| 118 | + |
| 119 | + private: |
| 120 | + void runOnFunc(FuncOp func) override { |
| 121 | + IRRewriter rewriter(func.getContext()); |
| 122 | + func.walk([&](TransferOp transfer) { |
| 123 | + if (auto arg = dyn_cast<BlockArgument>(transfer.getOperand())) { |
| 124 | + rewriter.moveOpBefore(transfer, arg.getOwner(), |
| 125 | + arg.getOwner()->begin()); |
| 126 | + } else { |
| 127 | + rewriter.moveOpAfter(transfer, transfer.getOperand().getDefiningOp()); |
| 128 | + } |
| 129 | + }); |
| 130 | + } |
| 131 | +}; |
| 132 | + |
| 133 | +} // namespace |
| 134 | + |
| 135 | +void AddSchedulingPreprocessingPasses(OpPassManager& pm, |
| 136 | + bool split_bwd_fragments, |
| 137 | + bool verify_schedule_units) { |
| 138 | + // The following seems like a good thing to always do, to keep the module |
| 139 | + // more tidy and merged, even if we are not going to actually do any |
| 140 | + // scheduling. |
| 141 | + // Move transfers to right after their producers. Without this pass, if we |
| 142 | + // have a producer fragment followed by transfers, then a consumer fragment, |
| 143 | + // even if the operands of the transfers are from a different producer |
| 144 | + // fragment, we are not able to merge the producer and consumer fragments. |
| 145 | + // This pass moves the transfers to right after the producer, which allows |
| 146 | + // the merge pass to do its job. |
| 147 | + pm.addNestedPass<FuncOp>(createMoveTransfersToProducerPass()); |
| 148 | + pm.addNestedPass<FuncOp>( |
| 149 | + createMergeUserDefinedFragmentsIntoSchedulingUnitsPass()); |
| 150 | + if (verify_schedule_units) { |
| 151 | + pm.addNestedPass<FuncOp>(createSchedulingUnitVerifierPass()); |
| 152 | + } |
| 153 | + |
| 154 | + // TODO(dvytin): Run split_bwd_fragments independently of the schedule. |
| 155 | + // |
| 156 | + // Furthermore, we now do the split after verification, which ensures that |
| 157 | + // the generic verification code we have still works. But we should consider |
| 158 | + // defining schedule-specific verification conditions (and even passes to |
| 159 | + // prepare the module for a given schedule.) |
| 160 | + // TODO(dvytin): Investigate how to define schedule-specific verification. |
| 161 | + if (split_bwd_fragments) { |
| 162 | + pm.addNestedPass<FuncOp>(createSplitBwdFragmentsPass()); |
| 163 | + // TODO(jupvfranco): Do we really need canonicalizations here? Tests seem to |
| 164 | + // fail without it. |
| 165 | + pm.addPass(createCanonicalizerPass( |
| 166 | + GreedyRewriteConfig().setRegionSimplificationLevel( |
| 167 | + GreedySimplifyRegionLevel::Disabled))); |
| 168 | + pm.addNestedPass<FuncOp>(createFragmentDcePass()); |
| 169 | + } |
| 170 | +} |
| 171 | + |
| 172 | +} // namespace mlir::mpmd |
0 commit comments