Repository navigation
Vectorize lorenz_curve and gini - #702
Smit-create wants to merge 1 commit into
Conversation
|
Hmm, The tests are already present in https://github.com/QuantEcon/QuantEcon.py/blob/main/quantecon/tests/test_inequality.py so I thought to skip adding them. |
|
Is this adding new features or refactoring the code? |
|
This is just refactoring the code and removing some |
|
@Smit-create It is usually advised to use for loops (and avoid creation of intermediate arrays) in |
I found this better in terms of time performance as this is vectorized version while the extra space complexity (creating new arrays) is still the same for both the functions -- O(n) |
|
@Smit-create thanks for opening this PR. Would you mind to update the top level comment box with a description of the change and document the performance improvements you mention in this thread so it's clear what this change is about. |
|
Thanks @mmcky. Done |
|
@Smit-create I haven't merged this as it isn't clear what level of performance improvement is being made. Is it 2% or 20% for example, it would be helpful to have timings between the different versions to make an assessment here. @oyamad makes a good point around |
There was a problem hiding this comment.
Pull Request Overview
This PR vectorizes the lorenz_curve and gini_coefficient functions to improve performance by replacing Python loops with NumPy vectorized operations. The changes eliminate explicit iteration in favor of array operations that can be optimized by NumPy's underlying C implementations.
Key changes:
- Replace manual loop-based cumulative calculations in
lorenz_curvewith vectorized NumPy operations - Optimize
gini_coefficientby reducing nested loops and using vectorized absolute difference calculations - Remove trailing whitespace
You can also share your feedback on Copilot code review for a chance to win a $100 gift card. Take the survey.
| """ | ||
|
|
||
| n = len(y) | ||
| n = y.shape[0] |
There was a problem hiding this comment.
[nitpick] Using y.shape[0] instead of len(y) is inconsistent with the pattern used elsewhere in the function (line 76 still uses len(y)). Consider keeping len(y) for consistency, as it works for both arrays and lists.
| n = y.shape[0] | |
| n = len(y) |
| i_sum[i] += abs(y[i] - y[j]) | ||
| return np.sum(i_sum) / (2 * n * np.sum(y)) | ||
| i_sum += np.sum(np.abs(y[i] - y)) | ||
| t_sum += y[i] |
There was a problem hiding this comment.
This vectorization still contains a loop over i and computes np.abs(y[i] - y) for each element, which may not provide the expected performance improvement. Consider fully vectorizing using broadcasting: np.sum(np.abs(y[:, np.newaxis] - y[np.newaxis, :])) to eliminate the loop entirely.
|
Thanks for this @Smit-create, and apologies that it sat open for so long. I've now benchmarked both branches to settle the question I raised above about the size of the performance improvement. The short version: the change is performance-neutral for Setup: numba 0.62.1, numpy 2.3.5, 10 cores, best-of-5 timings taken after JIT warm-up, Pareto(3) inputs. I ran the whole suite twice and the numbers below reproduced.
|
| n | main | this PR | speedup |
|---|---|---|---|
| 1,000 | 0.012 ms | 0.011 ms | 1.04x |
| 10,000 | 0.531 ms | 0.519 ms | 1.02x |
| 100,000 | 6.94 ms | 6.96 ms | 1.00x |
| 1,000,000 | 86.3 ms | 87.5 ms | 0.99x |
That spread is measurement noise. Both versions are O(n log n) dominated by the np.sort call, and the loop removed here is a trivial O(n) pass that numba already compiles to equivalent machine code. The change from len(y) to y.shape[0] also narrows the input types the function accepts, for no gain.
gini_coefficient — roughly 15% slower
| n | main | this PR | this PR vs main |
|---|---|---|---|
| 1,000 | 0.235 ms | 0.237 ms | 0.99x |
| 5,000 | 3.83 ms | 4.54 ms | 0.84x |
| 10,000 | 13.8 ms | 16.4 ms | 0.84x |
| 50,000 | 283 ms | 325 ms | 0.87x |
| 100,000 | 1155 ms | 1356 ms | 0.85x |
The cause is that np.sum(np.abs(y[i] - y)) allocates an n-element temporary array on every prange iteration, so the function performs n allocations of n elements each and the extra memory traffic outweighs what the vectorization buys back. The algorithm remains O(n²) either way, so this only moves the constant factor, and it moves it in the wrong direction.
Where the real win is
Gini has an O(n log n) closed form on sorted data, which is an algorithmic improvement rather than a constant-factor one:
| n | main (10-core parallel) | O(n log n) (single-threaded) | speedup |
|---|---|---|---|
| 1,000 | 0.235 ms | 0.0097 ms | 24x |
| 5,000 | 3.83 ms | 0.222 ms | 17x |
| 10,000 | 13.8 ms | 0.534 ms | 26x |
| 50,000 | 283 ms | 3.29 ms | 86x |
| 100,000 | 1155 ms | 6.89 ms | 168x |
The gap widens with n, and the sorted version beats the 10-core parallel implementation while running on a single thread. It agrees with the current implementation to 1e-9 on random Pareto data at all five sizes, and it satisfies the existing test_gini_coeff assertions for both Pareto and Weibull across every a in the 2–14 range that test samples from.
It also removes the library's only @njit(parallel=True), which is the browser blocker described in #926. I've updated that issue to make this rewrite the primary fix rather than the Emscripten platform gate it originally proposed.
Closing in favour of that work. Thanks again for the contribution, and for the profiling discussion in this thread — it's what led to identifying the larger win.
lorenz_curveandgini_coefficient.