Skip to content

Commit 8ceddca

Browse files
⚡️ Speed up function sigmoid_stable by 232%
Here is an optimized version of your function. The original code computes `np.exp(x)` twice for the `x < 0` case. To optimize, we can precompute the exponent, reducing redundant computation. This computes `np.exp(-np.abs(x))` once and reuses it for both cases, improving speed and efficiency for large arrays.
1 parent 8947ec9 commit 8ceddca

File tree

1 file changed

+2
-1
lines changed

1 file changed

+2
-1
lines changed

codeflash/process/infer.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22

33

44
def sigmoid_stable(x):
5-
return np.where(x >= 0, 1 / (1 + np.exp(-x)), np.exp(x) / (1 + np.exp(x)))
5+
exp_x = np.exp(-np.abs(x))
6+
return np.where(x >= 0, 1 / (1 + exp_x), exp_x / (1 + exp_x))
67

78

89
def postprocess(logits: np.array, max_detections: int = 8):

0 commit comments

Comments
 (0)