Skip to content

Towards kernel specialization and multi-versioning #12230

Open

Description

@antiagainst

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

  1. added
    runtime
    codegen
    platform/android 🤖
    on Feb 16, 2023
  2. self-assigned this
    on Feb 16, 2023
  3. antiagainst commented on Feb 16, 2023

    @antiagainst
    MemberAuthor

    I'm prototyping step 1 as listed in the above now.

  4. antiagainst commented on Feb 24, 2023

    @antiagainst
    MemberAuthor

    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 DeduplicateExecutables pass 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

    Model L0 L1 L2 L0/L2 L1/L2
    TF ResNet50 f32 75 39 20 3.75 1.95
    TF EfficientNetV2 Small f32 278 69 30 9.27 2.3
    TF BERT Large f32 413 15 14 29.5 1.07
    TFL PoseNet f32 48 27 14 3.43 1.93
    TFL MobileNetV2 f32 74 45 21 3.52 2.14
    TFL DeeplabV3 f32 78 44 22 3.55 2
    TFL PersonDetect f32 86 59 22 3.91 2.68
    TFL MobileSSD f32 121 84 34 3.56 2.47
    TFL MobileBERT f32 752 30 27 27.85 1.11
    TFL EfficientNetV2 Lite i8 136 96 32 4.25 3
    TFL MobileBERT i8 1452 168 162 8.96 1.04

    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.

  5. benvanik commented on Feb 24, 2023

    @benvanik
    Collaborator

    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!)

  6. ScottTodd commented on Feb 24, 2023

    @ScottTodd
    Member

    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.

  7. antiagainst commented on Feb 24, 2023

    @antiagainst
    MemberAuthor

    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

    Model L3 L0/L3 L1/L3
    TFL MobileBERT f32 20 37.6 1.5
    TFL MobileBERT i8 117 12.4 1.44

    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 after flow.dispatch.region before flow.dispatch.workgroups. I'd need more massaging of pass organization to enable those cases too.

  8. benvanik commented on Feb 24, 2023

    @benvanik
    Collaborator

    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?).

  9. antiagainst commented on Feb 24, 2023

    @antiagainst
    MemberAuthor

    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.

    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 values in hal.interface.constant.load ops!) 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.)

  10. antiagainst commented on Feb 24, 2023

    @antiagainst
    MemberAuthor

    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?).

    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.

  11. benvanik commented on Feb 24, 2023

    @benvanik
    Collaborator

    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).

  12. benvanik commented on Feb 24, 2023

    @benvanik
    Collaborator

    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 ;).

  13. 6 remaining items

  14. allieculp commented on Apr 19, 2023

    @allieculp

    @antiagainst Is this still in progress?

  15. antiagainst commented on Apr 19, 2023

    @antiagainst
    MemberAuthor

    Yes, this is still in progress.

  16. moved this from Not Started to In Progress in (Deprecated) IREEon Apr 19, 2023
  17. allieculp commented on May 15, 2023

    @allieculp

    @antiagainst Any update on this? Can we bump down to P2?

  18. antiagainst commented on May 15, 2023

    @antiagainst
    MemberAuthor

    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.

  19. moved this from In Progress to Backlog in (Deprecated) IREEon Aug 29, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

codegenplatform/android 🤖runtime

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions