Repository navigation
Description
This is the tracking issue for better support of kernel specialization and multi-versioning.
Rationale
IREE compiles various source models into deployable artifacts to target different hardware. At the source model level, we can see different model architectures, but largely these architectures are stacking/duplicating common layers; it can use the same exact shapes (e.g., transformers) or mutating ones (e.g., u-net and vision models). Thus, after dispatch region formation, we see lots of dispatches with similar structures but differing shapes. Right now we basically compile each of them separately. This causes quite a few issues, including slow compilation time and large memory consumption, duplicated code in deployable artifacts, slow on-device second-stage JIT compilation / startup time, etc. We need to reduce the specialization towards input workload shape here.
OTOH, esp. for deployment scenarios like mobile platforms where we don't control the hardware/software stack, we can see lots of variants w.r.t. accelerator (CPU, GPU, etc.) architectures. To be able to target such platforms broadly while retain good performance, we need to specialize towards major architectural differences (e.g., 16-bit/8-bit computation supported or not, having special matrix/vector compute unit or not, etc.). Note that we have a much smaller surface area here compared to input workload shape--we only have a few CPU/GPU vendors, each with a few generations of hardware architecture; and they resemble each other mostly.
Plans
There are a few planned steps to fully make this happen:
1. Reduce kernel specialization towards input workload shapes
The approach would be to erase static shape information after dispatch region formation, so that we can deduplicate different dispatches with the same op sequence but different shapes. There are trade-offs here w.r.t. how much we erase and what information are retained / being more coarse grained and passed down to CodeGen to facilitate tile sizes planning etc.
Better deduplication calls for erasing more information; the ultimate version would be to erase all static dimensions. Fortunately, after erasing the shape information and performing executable deduplication at flow level, at stream level we already have passes (FoldUniformOperands) to look at all dispatch call sites to inline back constants that have the same value across all sites, and deduplicate operands that are correlated at all dispatch sites too. So this gives us back some static information. For those call sites that are differ, we have all the possible values captured in hal.interface.constant.load for each dimension (which originally comes from stream AnnotateDispatchArguments pass); the CodeGen can feel free to decide how to generate code by looking at all possible values--how many versions, what tile size to use for each version, etc.
Dynamicizing static shapes would need to happen after flow.dispatch.region formation and before flow.dispatch.workgroup formation, to see the full dispatch (in the former), and also avoid the complication of manipulating materialized explicit captures (in the latter). In the CodeGen, we'd need to factor in the "side channel" shape information from hal.interface.constant.load to simplify the IR, like eliminating affine.min ops for bounds checking, etc.
2a. Run multiple CodeGen pipelines for the same input dispatch region
Multi-versioning torwards different architectures boils down invoking multiple (different) CodeGen pipelines over the same original dispatch region, with each invocation assuming different target environment. There is some policy layer to be built here---we need to decide what variants we care about and so want to generate. But largely we aren't expecting to see a ton of options here because of the low level nature of CodeGen pipeline operates--we work on matmul / convolution / reduction / etc. On GPU, for matmul likely we need SIMT, cooperative matrix / tensorcore version, etc. For convolution, direct convolution, winograd, implicit gemm, etc. Just a few.
Right now the CodeGen pipelines are set up to run only once for each input dispatch region. Making it multiple invocations won't be too hard. For example, we can just have another pass before hand to duplicate the input and annotate with different target environments and pipeline selections, and then leverage existing flows.
2b. Generate runtime kernel selection logic
Right now we compile kernels by giving a specific target triple and then invoke it on the exact same expected target hardware. This usage pattern won't need rigorous runtime checks to make sure the hardware capability assumptions made by the kernel is met. So right now this part is sort of broken. In order to make multi-versioning work better, we'd need to fix the connection between kernel capability requirements and runtime checks.
This would mean we need to have additional attributes / regions on top of hal.executable.export, in addition to the workgroup count calculation logic. When we CodeGen multi-versions of kernels, we at the same time emit host logic to query the target environment and do selection over the CodeGen'd versions. There is policy layer here too--different backends would want different parameters to be queried. But the mechanism remains similar and we already have it in HAL, for querying int64 values.
3. Consider device parallelism to further dynamic adjust kernel launches
The next step with the above two done, is to push further to make the system more responsive to the target environment. Most of the time the top one concern for GPU at least is to fully saturate the GPU with work. That means different tile / reuse strategies with different hardware. For the same workload, a weak GPU is fine with large tile sizes maybe, but a beefy GPU would likely need to let each thread do less work to fully utilize the full GPU. So we'd like to have logic at the runtime to query the device parallelism and then using host logic to compute tile / workgroup sizes, etc.
Cross-vendor parallelism querying extensions is non-existing for Vulkan right now; but probably we can build known architectures into a simple database to embed (again, not a lot of hardware vendors; not a lot of architectures). Similarly for CPU and CUDA. It also means some of the tile / workgroup deduction logic happening in C++ would be CodeGen'd into arith op computations to be run on host. How much we can do here remains to be explored and prototyped.
Activity
antiagainst commentedon Feb 16, 2023
I'm prototyping step 1 as listed in the above now.
antiagainst commentedon Feb 24, 2023
Some initial statistics after erasing static shape from dispatch regions. Right now my prototype considers tensor values and ops and erases them. It does not yet touch slice offsets & sizes. The following are numbers reported by the
DeduplicateExecutablespass statistics.L0: without any deduplication
L1: normal deduplication + don't inline constants (
--iree-flow-inline-constants-max-byte-length=0)L2: L1 + dynamicize static tensor shapes
This alone is already giving good reduction--typically 2x and more on top of L1. For those small improvements on top of L1, the issues are actually already sort of captured by Scott's nice analyses previously. My next steps would be to look into them, particularly slice offsets and sizes.
benvanik commentedon Feb 24, 2023
Wow, really nice breakdown Lei! In my mind deduplication is compression, and 10x compression wins are fantastic let alone 30x :P Really interested to see what the dynamic offsets/sizes yield, and if that particularly helps the mobilebert i8 (162 still feels high, but 162 is way better than 1452!)
ScottTodd commentedon Feb 24, 2023
Exciting! It's looking like we'll have a set of orthogonal techniques that can be applied in different combinations for progressive benefits. These sorts of optimizations would be trickier to maintain if they were overly reliant on a particular IR structure or pass sequencing.
antiagainst commentedon Feb 24, 2023
Some further numbers after dynamicize slice offsets and sizes. Only measured on MobileBERT given that's the lest improved cases:
L3: dynamic tensor shapes (L2) + dynamic slice offset/size
This is still not covering all extract/insert slice cases though--the case where we have pairing load/store for copying, as pointed out by Scott previously, still remains. This is due to how we handle those ops. They are generated when converting to
flow.dispatch.workgroups, while my prototype does stuff afterflow.dispatch.regionbeforeflow.dispatch.workgroups. I'd need more massaging of pass organization to enable those cases too.benvanik commentedon Feb 24, 2023
Nice 1452->117 is a fantastic drop! How many of those copy dispatches are there in what's left? We should really look at eliminating those entirely (maybe related to pad fusion?).
antiagainst commentedon Feb 24, 2023
Yup. I'm measuring sort of the ultimate cases where we turn all dimensions into question marks so unique as much as possible; backends can decide to multi-versioning by looking at concrete values behind the question marks (thanks to Ben's magic
valuesinhal.interface.constant.loadops!) according later for performance purposes.I'd also expect these transforms to be generally applicable and complementary to other techniques like layout optimizations (which could also affect the number of executables generated.)
antiagainst commentedon Feb 24, 2023
Not a lot left specifically for MobileBERT. Here is the current model when
-compile-to=flow. So just a few more. I do see more cases in vision/convolution models though (particularly due to how we handle convolution padding). Good to clean it up though. The major issue for MobileBERT, esp. for quantized version, is around fusion and the slight variants of fused elementwise ops. We'd probably need some more sophisticated logic to dedup there, or at least there is a trade-off between fusion and executable count to make.benvanik commentedon Feb 24, 2023
Very true! We'd talked about doing layout canonicalization ages ago but I don't think we ever got anything implemented. FoldUniformOperands/FuseDispatchBindings/PackDispatchOperands all kind of do stuff similar to it. One thing I've wanted to do for awhile was move the DeduplicateExecutables pass into Util/ as SymbolCSE and add a util interface for SymbolCSE'able ops like executables - then we could run it in flow like we do today, in stream after all the layout optimization, and in hal after translation (dedupe variants that may have ended up with the same IR).
benvanik commentedon Feb 24, 2023
Ugh that apply_scale IR with all those cmps/selects kills me x_x could probably halve our compile time if we had a clamp op and shrunk the IR 4x!
Yeah the slight op content variants will be tricky but there's probably some simple heuristics that'll cover most of them (🤞). Off the top of my head we could do a comparison and if the delta is a single sequence of ops then we insert an i1 arg at all dispatch sites and an if around the conditional ops (or a select). The PackDispatchOperands pass will end up combining those into a bitfield (IIRC, if not I'll finish that :) and the potential values set during executable translation would have all unique combinations of bits allowing for the backend to decide which to materialize. Maybe once your stuff is ready and we have the IR we can extract some samples and try doing that by hand to see how much it'd help (I suspect a lot given my skimming, but there's a lot of cmpi/select noise in there ;).
[flow] NFC: Move code for cloning producers into RegionOpUtils (#12349)
6 remaining items
[flow] NFC: Move code for cloning producers into RegionOpUtils (iree-…
[flow] Move CloneProducersIntoDispatchRegions into its own pass (iree…
allieculp commentedon Apr 19, 2023
@antiagainst Is this still in progress?
antiagainst commentedon Apr 19, 2023
Yes, this is still in progress.
[flow] NFC: Move code for cloning producers into RegionOpUtils (#12349)
[flow] Move CloneProducersIntoDispatchRegions into its own pass (#12375)
[flow] NFC: Move code for cloning producers into RegionOpUtils (iree-…
[flow] Move CloneProducersIntoDispatchRegions into its own pass (iree…
allieculp commentedon May 15, 2023
@antiagainst Any update on this? Can we bump down to P2?
antiagainst commentedon May 15, 2023
I haven't been able to push on this recently; and given the upcoming re-prioritization I won't be able to handle this in a while too. So yeah I moved this to P2.
[flow] NFC: Move code for cloning producers into RegionOpUtils (iree-…
[flow] Move CloneProducersIntoDispatchRegions into its own pass (iree…