⚡️ Speed up method KalmanFilterXYWH.predict by 85%
#40
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.
📄 85% (0.85x) speedup for
KalmanFilterXYWH.predictinultralytics/trackers/utils/kalman_filter.py⏱️ Runtime :
16.0 milliseconds→8.60 milliseconds(best of194runs)📝 Explanation and details
The optimized code achieves an 85% speedup by eliminating inefficient NumPy operations and Python overhead. The key optimizations are:
What was optimized:
Eliminated
np.r_concatenation: The original code usednp.r_[std_pos, std_vel]which is inefficient for small arrays. The optimized version pre-computes values and usesnp.concatenate()directly.Reduced repeated multiplications: Instead of computing
self._std_weight_position * mean[2]four times, the optimized code cachesw = mean[2]andh = mean[3]to avoid redundant array indexing.Replaced
np.square()with direct multiplication: Changednp.square(np.r_[...])tostds * stds, which is faster for element-wise squaring.Used
@operator overnp.linalg.multi_dot: For the 3-matrix multiplication,A @ B @ Cis more optimized thannp.linalg.multi_dot((A, B, C))in modern NumPy.Why it's faster:
The line profiler shows the original
np.diag(np.square(np.r_[std_pos, std_vel]))took 59.7% of total runtime, while the optimized version's equivalent operations only take 28.9%. This is becausenp.r_creates intermediate objects and performs type checking, while direct concatenation is more efficient.Impact on workloads:
The optimizations are most effective for:
The optimizations maintain identical numerical results while being particularly beneficial for high-frequency prediction calls typical in video tracking systems.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-KalmanFilterXYWH.predict-mir99zmland push.