A2Easy★ Core Essential · Industrial BedrockPart A · Core Kernels & Activation Functions

Numerically Stable Sigmoid & Log-Sigmoid

⚡Flashcard Drill➔

Piecewise formulation avoiding overflow on large negatives; Log-Sigmoid powered by logaddexp for robust BCE training.

⏱️ Time: O(N)
💾 Space: O(N)
🎯 Interactive Self-Practice Loop (Attempt Before Peeking)
Practice in 4 steps: recall mechanism, complete core lines, check edge cases, and log mastery locally.
Step 1 · Mechanism Recall & Stability Self-Check
Step 2 · Complete Key Implementation Lines
import numpy as np
def stable_sigmoid(z: np.ndarray) -> np.ndarray:
"""Piecewise evaluation to prevent overflow for large negative z."""
out = np.empty_like(z, dtype=np.float64)
pos_mask = z >= 0
out[pos_mask] =
exp_z = np.exp(z[~pos_mask])
out[~pos_mask] = exp_z / (1.0 + exp_z)
return out
def stable_log_sigmoid(z: np.ndarray) -> np.ndarray:
"""Stable log(sigmoid(z)) using logaddexp."""
return
Step 3 · Verify Boundary Cases & Assertions
Step 4 · Follow-Up Drill & Review Outcome
Q1: Why fuse Sigmoid and BCE into a single BCEWithLogitsLoss operator?
Next: Gaussian Error Linear Unit (GELU) →
💡

Core Mental Anchor / Mnemonic

Standard form for positives, multiply exp(z) for negatives; use logaddexp for log-sigmoid

📐 Mathematical Derivation & Core Formula

σ(z)=11+e−z,log⁡σ(z)=−log⁡(1+e−z)=−logaddexp(0,−z)\sigma(z) = \frac{1}{1 + e^{-z}}, \quad \log \sigma(z) = -\log(1 + e^{-z}) = -\mathrm{logaddexp}(0, -z)
### Numerical Defense & Formulation
When z≪0z \ll 0, −z≫0-z \gg 0, directly evaluating e−ze^{-z} overflows.
For z<0z < 0, multiply numerator and denominator by eze^z:
σ(z)=ez1+ez\sigma(z) = \frac{e^z}{1 + e^z}
Because ez∈(0,1]e^z \in (0, 1], overflow is completely avoided.

For log⁡σ(z)\log \sigma(z), negative saturation yields log⁡(0)=−∞\log(0) = -\infty. We use the exact identity −log⁡(1+e−z)=−logaddexp(0,−z)-\log(1 + e^{-z}) = -\mathrm{logaddexp}(0, -z) to retain full precision.

🔄 Tensor Dimensions & Shape Flow

(...) -> partition into pos/neg masks -> piecewise exp -> combine back to (...)

🛡️ Numerical Stability & Pitfalls Checklist

  • Do not evaluate 1.0 / (1.0 + np.exp(-z)) unconditionally
  • Never compute Log-Sigmoid as np.log(sigmoid(z)); use np.logaddexp(0.0, -z)
  • Sigmoid derivative satisfies d_sigmoid = s * (1.0 - s)

💻 Reference Code Implementation

import numpy as np

def stable_sigmoid(z: np.ndarray) -> np.ndarray:
    """Piecewise evaluation to prevent overflow for large negative z."""
    out = np.empty_like(z, dtype=np.float64)
    pos_mask = z >= 0
    out[pos_mask] = 1.0 / (1.0 + np.exp(-z[pos_mask]))
    exp_z = np.exp(z[~pos_mask])
    out[~pos_mask] = exp_z / (1.0 + exp_z)
    return out

def stable_log_sigmoid(z: np.ndarray) -> np.ndarray:
    """Stable log(sigmoid(z)) using logaddexp."""
    return -np.logaddexp(0.0, -z)

🧪 Runnable Assertions & Validation

Copy and run directly in Python / Jupyter:

import numpy as np
z = np.array([-1000.0, 0.0, 1000.0])
s = stable_sigmoid(z)
assert s[0] == 0.0 and s[1] == 0.5 and s[2] == 1.0
assert not np.isnan(s).any()
ls = stable_log_sigmoid(z)
assert not np.isneginf(ls[0]), "Extreme negatives should not return -inf"
assert np.isclose(ls[0], -1000.0), f"Actual: {ls[0]}"
print("✓ Sigmoid assertion passed")

🎯 Core Follow-up Inquiries & Reference Answers

Q1:Why fuse Sigmoid and BCE into a single BCEWithLogitsLoss operator?
Fusing them eliminates intermediate activation round-trips to HBM and computes max⁡(x,0)−xy+log⁡(1+e−∣x∣)\max(x, 0) - xy + \log(1 + e^{-|x|}), preventing gradient vanishing and log(0) errors.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔
← Prev: Numerically Stable SoftmaxBack to Part A & All 105Next: Gaussian Error Linear Unit (GELU) →
中文速览与面试要点

Sigmoid 与 Log-Sigmoid(数值稳定)

正负区间分段避免大负数指数溢出,Log-Sigmoid 采用 logaddexp 解决二元损失下溢。

核心要点

  • ### 数学机理与双向防御 当 z 0 时,-z 0,e^-z 会迅速引发指数上溢(Overflow)。 当 z < 0 时,分子分母同乘 e^z: (z) = e^z1 + e^z 此时因 z < 0,e^z (0, 1),上溢彻底消除。 对于 (z),当 z 极负时,直接计算 ( (z)) 会因为 (z) 下溢为 0 而得到 - 。通过等价变换 - (1 + e^-z) = - logaddexp(0, -z),调用底层的 Log-Sum-Exp 保持数值鲁棒。
  • (...) -> pos/neg 掩码划分 -> 分段 exp 计算 -> 合并输出 (...)
  • 切忌直接返回 1.0 / (1.0 + np.exp(-z)),在 z < -709 时直接报溢出警告或返回 0
  • Log-Sigmoid 切忌写成 np.log(sigmoid(z)),必须使用 np.logaddexp
  • 梯度导数计算:d_sigmoid = s * (1.0 - s)
  • 为什么在二元交叉熵损失(BCEWithLogitsLoss)中通常将 Sigmoid 和 BCE 合并为一个算子?:合并后损失函数为 (x, 0) - x y + (1 + e^-|x|),省去了一次独立的显存读取,消除了 Sigmoid 极值导致的梯度饱和与 log(0) 崩溃。

参考实现

import numpy as np

def stable_sigmoid(z: np.ndarray) -> np.ndarray:
    """Piecewise evaluation to prevent overflow for large negative z."""
    out = np.empty_like(z, dtype=np.float64)
    pos_mask = z >= 0
    out[pos_mask] = 1.0 / (1.0 + np.exp(-z[pos_mask]))
    exp_z = np.exp(z[~pos_mask])
    out[~pos_mask] = exp_z / (1.0 + exp_z)
    return out

def stable_log_sigmoid(z: np.ndarray) -> np.ndarray:
    """Stable log(sigmoid(z)) using logaddexp."""
    return -np.logaddexp(0.0, -z)