[Metal backend] Optimize While/BatchMatMul OP via 4x4 Register Blocking#4282
Merged
wangzhaode merged 2 commits intoalibaba:masterfrom Mar 19, 2026
Merged
[Metal backend] Optimize While/BatchMatMul OP via 4x4 Register Blocking#4282wangzhaode merged 2 commits intoalibaba:masterfrom
While/BatchMatMul OP via 4x4 Register Blocking#4282wangzhaode merged 2 commits intoalibaba:masterfrom
Conversation
Implement safe and unsafe paths in matrix multiplication kernel. The unsafe path is used when indices are guaranteed to be within bounds for performance, while the safe path includes conditional checks and zero-padding for boundary elements to prevent invalid memory access.
bitxsw93
approved these changes
Mar 19, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Environment
Motivation
When benchmarking YOLOv8-Worldv2 models, I found their latencies on
Metal (80 ms)backend were much slower thanCPU (35 ms).The
timeProfiletools shows that theWhile (actually BatchMatMul is calling While)OP takes59 mson Metal backend while CPU only takes7 msThen I asked Gemini and found that the implementation of
loop_matmulinsource/backend/metal/MetalLoop.mmis naive and not well optimized.Solution
Optimize
loop_matmulusing 4x4 register blocking and 2D dispatch grid.Benchmarking
In which the cost of
WhileOP is reduced by 59.63/7.43=8x faster.