Commit 474b6ea
authored
⚡️ Speed up function
Here’s an optimized version of your code with the following improvements.
- **Avoid repeated computation**: np.exp(logits) was computed more than once per value in sigmoid_stable. Cache where possible.
- **Avoid flattening with reshape**: Use .ravel() for a fast view rather than .reshape if you don't need a copy.
- **Vectorized selection**: Use np.argpartition for O(n) partial selection instead of full sort (np.argsort) when only top K needed; sort only those afterward for correct order.
- **Preallocate output**: Preallocate fixed-size array when possible.
Here’s the improved code.
**Notes:**
- `sigmoid_stable` does not call np.exp(x) and np.exp(-x) separately for each value, instead using `np.exp(-np.abs(x))`, making it slightly faster and more numerically stable.
- Uses `np.argpartition(..., k)` to efficiently get top K indices. Only these are then sorted by value.
- `.ravel()` instead of `.reshape(-1)` for flattening, which is faster when possible.
- Output structure and function signatures are preserved.
- All comments are kept unless relating to changed code.
This should noticeably speed up use on large arrays or large batch sizes.postprocess by 210%1 parent 102b4b6 commit 474b6ea
1 file changed
+35
-0
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
0 commit comments