Module contents
Lesson 13 of 20Advanced 90 min

Laplace's method and asymptotic approximations

Approximate integrals depending on a large parameter, ∫e^{n f(x)}dx, by replacing the integrand with a Gaussian centered at the maximum. This yields Stirling's formula, the temperature behavior of logsumexp and softmax, and the idea that becomes the Laplace approximation of a posterior in m14. Asymptotic series are introduced: they may diverge while remaining excellent approximations.

After this lesson you can

  • Derive Laplace's method in one and several variables, including its leading term and error order.
  • Prove Stirling's formula from the Gamma function.
  • Bound logsumexp between the maximum and the maximum plus τ·log n, and relate its gradient to softmax.
  • Distinguish convergent and asymptotic series and select optimal truncation of an asymptotic series.
  • Implement Laplace approximations of normalization constants and measure their error against quadrature.

Before you start

Motivation: integrals dominated by one point

A family of integrals and sums appears everywhere in machine learning and almost never has a closed form: those depending on a large parameter multiplying an exponent.

  • Normalization constants. With nn independent observations, the Bayesian posterior of a parameter θ\theta is p(θ∣D)∝p(θ)∏i=1np(xi∣θ)=exp⁡(n ℓˉn(θ))p(\theta \given \Data) \propto p(\theta)\prod_{i=1}^n p(x_i \given \theta) = \exp\big(n\,\bar\ell_n(\theta)\big), where ℓˉn\bar\ell_n is the average log likelihood plus the log prior divided among the nn observations. The missing constant, Z=∫enℓˉn(θ) ⁣dθZ = \int e^{n\bar\ell_n(\theta)}\dd\theta, is the model evidence: it compares models, selects hyperparameters and gives the BIC criterion. Integrating in Rd\R^d with dd in the thousands is impossible by quadrature.
  • Giant factorials. n!=Γ(n+1)=∫0∞enln⁡x−x ⁣dxn! = \Gamma(n + 1) = \int_0^\infty e^{n\ln x - x}\dd x. Counting configurations, estimating binomial coefficients or calculating count entropies requires knowing how n!n! grows when nn is of order 10610^{6}, long before the number can be written down.
  • Softmax with temperature. Transformer attention, LLM sampling and soft Bellman operators calculate τlog⁡∑iezi/τ\tau\log\sum_i e^{z_i/\tau} and its gradient. This is a sum, not an integral, but with n=1/τn = 1/\tau has exactly the same form ∑ienzi\sum_i e^{n z_i}, and the question is the same: what happens as nn grows.

All three feature enfe^{n f} with large nn, and an exponential with a large exponent amplifies differences dramatically: if f(x1)−f(x2)=0.1f(x_1) - f(x_2) = 0.1, with n=1000n = 1000 the integrand at x1x_1 is e100≈1043e^{100} \approx 10^{43} times larger than at x2x_2. All mass concentrates around the maximum of ff, and near the maximum any smooth function is a parabola. The exponential of a parabola is Gaussian, and Gaussians can be integrated. This is the whole idea of Laplace’s method. This lesson turns it into a theorem with precise assumptions and error order, extends it to several variables, derives Stirling’s formula and logsumexp behavior, studies failure cases and ends with a surprising phenomenon: successive corrections form divergent series that are nonetheless extraordinary approximations.

Intuition: the peak becomes Gaussian

Take f(x)=cos⁡xf(x) = \cos x on (−π,π)(-\pi, \pi). Its maximum is at x∗=0x^* = 0, where cos⁡x=1−x2/2+O(x4)\cos x = 1 - x^2/2 + \bigO(x^4). Factoring out the value at the maximum,

∫−ππencos⁡x ⁣dx=en∫−ππen(cos⁡x−1) ⁣dx≈en∫−∞∞e−nx2/2 ⁣dx=en2πn.\int_{-\pi}^{\pi} e^{n\cos x}\dd x = e^{n}\int_{-\pi}^{\pi} e^{n(\cos x - 1)}\dd x \approx e^{n}\int_{-\infty}^{\infty} e^{-n x^2/2}\dd x = e^{n}\sqrt{\frac{2\pi}{n}}.

There are two approximations in that ≈\approx: replacing cos⁡x−1\cos x - 1 by its osculating parabola and extending the interval to the entire line. Both improve with nn, because the normalized integrand en(cos⁡x−1)e^{n(\cos x - 1)} has width of order 1/n1/\sqrt{n}: as nn grows, only an increasingly small neighborhood of the maximum matters, where the parabola becomes increasingly accurate, and what lies outside the interval is a negligible Gaussian tail.

InteractiveThe peak becomes Gaussian
f(x)=cos⁡x en (−π,π)f(x) = \cos x \text{ en } (-\pi, \pi)
Normalized integrand en(f(x)−f∗)e^{n(f(x) - f^*)} with n=8.0n = 8.0
Relative error ∣Laplace/exact−1∣|\text{Laplace}/\text{exact} - 1|
  • Laplace
  • 1/(8n)
  • exact integrand
  • Laplace Gaussian at the global maximum
Function ff
8.0
Exact e−nf∗ ⁣∫enfe^{-nf^*}\!\int e^{nf}0.90121
Laplace 2π/(n∣f′′∣)\sqrt{2\pi/(n|f''|)}0.88623
Maximum x∗x^* and curvature −f′′(x∗)-f''(x^*)0.000 · 1.000
Relative error−1.66 %
n⋅n\cdot error−0.1330
Interior nondegenerate maximum: relative error is ≈−1/(8n)\approx -1/(8n). At n=8.0n = 8.0, n⋅n\cdoterror =−0.1330= −0.1330 versus −0.125-0.125.
On the left, the function ff above and normalized integrand en(f(x)−f∗)e^{n(f(x) - f^*)} (blue) below, with the Laplace Gaussian at the maximum (orange); on the right, relative error versus nn on log-log axes. Increase nn: the integrand narrows and merges with the Gaussian, and error falls along line c/nc/n. Compare the constant n⋅n\cdoterror with −1/8-1/8 for cos⁡x\cos x and with −1/12-1/12 for ln⁡t−t\ln t - t. Then try the three pathological cases: with two peaks, which has more mass for n=10n = 10? At the boundary, what factor is missing? With a degenerate maximum, at what rate does the correction error fall?

The right-hand graph shows something the informal argument does not: relative error not only tends to zero, it does so exactly like c/nc/n, with a constant depending on the third and fourth derivatives of ff at the maximum. And the two-peak case shows the method’s limit: “asymptotic” means “as n→∞n \to \infty,” and for a particular nn a slightly lower but much wider maximum can contribute most of the integral.

Laplace’s method in one variable

This approximation is Laplace’s method: replace the integrand by the Gaussian with the same maximum and curvature there. The three assumptions play concrete roles. The first gives the parabola, through the second derivative test. The second prevents another region of the domain from competing with the maximum: without it, a sequence of local maxima approaching the height of f(x∗)f(x^*) at infinity might contribute as much mass as the peak. The third guarantees finite tails for some nn, and therefore for all larger values.

Proof

Without loss of generality, x∗=0x^* = 0 and f(0)=0f(0) = 0 (translate the variable and factor out enf(x∗)e^{nf(x^*)}). Let A=−f′′(0)>0A = -f''(0) > 0 and fix ε∈(0,A)\eps \in (0, A). By continuity of f′′f'' there is δ>0\delta > 0 with ∣f′′(x)+A∣<ε\abs{f''(x) + A} < \eps if ∣x∣<δ\abs{x} < \delta. By the Lagrange remainder, for ∣x∣<δ\abs{x} < \delta there exists ξ\xi between 00 and xx with f(x)=12f′′(ξ)x2f(x) = \tfrac12 f''(\xi)x^2, so

−12(A+ε) x2≤f(x)≤−12(A−ε) x2(∣x∣<δ).-\tfrac12(A + \eps)\,x^2 \le f(x) \le -\tfrac12(A - \eps)\,x^2 \qquad (\abs{x} < \delta).

Central part. Integrating the upper bound over the entire line and using the Gaussian integral ∫Re−cx2/2 ⁣dx=2π/c\int_\R e^{-cx^2/2}\dd x = \sqrt{2\pi/c},

∫−δδenf≤2πn(A−ε),∫−δδenf≥∫−δδe−n(A+ε)x2/2 ⁣dx=2πn(A+ε) (1−qn),\int_{-\delta}^{\delta} e^{nf} \le \sqrt{\frac{2\pi}{n(A - \eps)}}, \qquad \int_{-\delta}^{\delta} e^{nf} \ge \int_{-\delta}^{\delta} e^{-n(A+\eps)x^2/2}\dd x = \sqrt{\frac{2\pi}{n(A + \eps)}}\,\big(1 - q_n\big),

where qnq_n is the probability that a centered normal of variance 1/(n(A+ε))1/(n(A + \eps)) lies outside (−δ,δ)(-\delta, \delta), which tends to 0.

Tails. By assumption 2, η=−sup⁡∣x∣≥δf(x)>0\eta = -\sup_{\abs{x} \ge \delta} f(x) > 0. For n≥n0n \ge n_0, in region ∣x∣≥δ\abs{x} \ge \delta we have enf=e(n−n0)fen0f≤e−(n−n0)ηen0fe^{nf} = e^{(n - n_0)f}e^{n_0 f} \le e^{-(n - n_0)\eta}e^{n_0 f}, so

∫∣x∣≥δenf≤e−(n−n0)η∫aben0f,\int_{\abs{x} \ge \delta} e^{nf} \le e^{-(n - n_0)\eta}\int_a^b e^{n_0 f},

which is exponentially small and, multiplied by n\sqrt{n}, still tends to 0.

Conclusion. Multiplying everything by nA/(2π)\sqrt{nA/(2\pi)} and taking limits,

AA+ε≤lim inf⁡n→∞I(n)2π/(nA)≤lim sup⁡n→∞I(n)2π/(nA)≤AA−ε.\sqrt{\frac{A}{A + \eps}} \le \liminf_{n\to\infty} \frac{I(n)}{\sqrt{2\pi/(nA)}} \le \limsup_{n\to\infty} \frac{I(n)}{\sqrt{2\pi/(nA)}} \le \sqrt{\frac{A}{A - \eps}}.

Since ε\eps is arbitrary, the ratio tends to 1.

∎

The proof also explains the scale order. Relevant width is 1/nA1/\sqrt{nA}, so the region that matters shrinks; what happens at fixed distance δ\delta from the maximum is penalized by e−nηe^{-n\eta}, much smaller than any power of nn. Thus the method needs only local information at the maximum and a global condition ruling out competitors.

The error order: the first correction

To see why error is O(1/n)\bigO(1/n), and with what constant, change to the natural variable y=n (x−x∗)y = \sqrt{n}\,(x - x^*), in which the Gaussian has fixed width. Write A=−f′′(x∗)A = -f''(x^*), f3=f′′′(x∗)f_3 = f'''(x^*) and f4=f(4)(x∗)f_4 = f^{(4)}(x^*).

I(n)=enf∗n∫exp⁡(−Ay22+f3 y36n+f4 y424 n+⋯) ⁣dy\begin{aligned} I(n) = \frac{e^{nf^*}}{\sqrt n}\int \exp\Big(&-\frac{A y^2}{2} + \frac{f_3\,y^3}{6\sqrt n} \\ &+ \frac{f_4\,y^4}{24\,n} + \cdots\Big)\dd y \end{aligned}
Taylor expansion of n(f(x∗+y/n)−f∗)n\big(f(x^* + y/\sqrt n) - f^*\big): the term of degree kk has factor n1−k/2n^{1 - k/2}.
1/4

The calculation is formal (it interchanges series and integral), but is made rigorous by the same scheme as the proof: cut off at ∣x−x∗∣<δn\abs{x - x^*} < \delta_n with δn→0\delta_n \to 0 slowly, bound the Taylor remainder and the tails are exponentially small. With ff of class C4C^4 it gives the theorem’s error O(1/n)\bigO(1/n), and with C6C^6, the expansion through O(n−2)\bigO(n^{-2}). Two checks using the figure:

  • f=cos⁡xf = \cos x: A=1A = 1, f3=−sin⁡0=0f_3 = -\sin 0 = 0, f4=cos⁡0=1f_4 = \cos 0 = 1, hence c1=1/8c_1 = 1/8. The exact integral is 2πI0(n)2\pi I_0(n), with I0I_0 the modified Bessel function, and indeed 2πI0(n)=2π/n en (1+1/(8n)+⋯ )2\pi I_0(n) = \sqrt{2\pi/n}\,e^n\,(1 + 1/(8n) + \cdots).
  • f=ln⁡t−tf = \ln t - t: A=1A = 1, f3=2f_3 = 2, f4=−6f_4 = -6, hence c1=−6/8+20/24=1/12c_1 = -6/8 + 20/24 = 1/12. That 1/121/12 is the first correction in Stirling’s formula, as you will soon see.

The error measured by the figure is that of the leading term, Laplace/exacto−1≈−c1/n\text{Laplace}/\text{exacto} - 1 \approx -c_1/n: that is why n⋅n\cdoterror stabilizes at −0.125-0.125 and −0.0833-0.0833.

With a prefactor

Almost always the integral has a factor that does not grow with nn, ∫g(x)enf(x) ⁣dx\int g(x)e^{nf(x)}\dd x. If gg is continuous at x∗x^* with g(x∗)≠0g(x^*) \neq 0 and ∫∣g∣en0f<∞\int \abs{g}e^{n_0f} < \infty, the same proof gives

∫abg(x) enf(x) ⁣dx∼g(x∗)2πn ∣f′′(x∗)∣  enf(x∗).\int_a^b g(x)\,e^{nf(x)}\dd x \sim g(x^*)\sqrt{\frac{2\pi}{n\,\abs{f''(x^*)}}}\;e^{nf(x^*)}.

The slow factor is evaluated at the maximum and taken outside. This matters for a posterior’s prior: the prior does not scale with nn and enters only through p(θ^)p(\hat\theta).

The multivariable case

In Rd\R^d the parabola becomes a quadratic form defined by the Hessian, and the one-dimensional Gaussian becomes a multivariate Gaussian.

Proof

With x∗=0\vb{x}^* = \vb{0}, f(0)=0f(\vb{0}) = 0 and A=−H\mat{A} = -\mat{H}, which is positive definite. By the multivariable Taylor theorem with Lagrange remainder, f(x)=12x⊤∇2f(ξ)xf(\vb{x}) = \tfrac12\vb{x}\T\hess f(\boldsymbol{\xi})\vb{x} with ξ\boldsymbol\xi on the segment from 0\vb{0} to x\vb{x}. Given ε\eps less than the smallest eigenvalue of A\mat{A}, Hessian continuity gives a ball ∥x∥<δ\norm{\vb{x}} < \delta on which ∥∇2f(x)+A∥2<ε\norm{\hess f(\vb{x}) + \mat{A}}_2 < \eps, and therefore

−12x⊤(A+εI)x≤f(x)≤−12x⊤(A−εI)x.-\tfrac12\vb{x}\T(\mat{A} + \eps\mat{I})\vb{x} \le f(\vb{x}) \le -\tfrac12\vb{x}\T(\mat{A} - \eps\mat{I})\vb{x}.

For any positive-definite B\mat{B}, the change of variables x=B−1/2u/n\vb{x} = \mat{B}^{-1/2}\vb{u}/\sqrt{n}, with Jacobian n−d/2det⁡(B)−1/2n^{-d/2}\det(\mat{B})^{-1/2}, converts the Gaussian integral into a product of dd one-dimensional integrals:

∫Rde−nx⊤Bx/2 ⁣dx=n−d/2det⁡(B)−1/2∫Rde−∥u∥2/2 ⁣du=(2πn)d/2det⁡(B)−1/2.\int_{\R^d} e^{-n\vb{x}\T\mat{B}\vb{x}/2}\dd\vb{x} = n^{-d/2}\det(\mat{B})^{-1/2}\int_{\R^d} e^{-\norm{\vb{u}}^2/2}\dd\vb{u} = \Big(\frac{2\pi}{n}\Big)^{d/2}\det(\mat{B})^{-1/2}.

Tails outside the ball are handled exactly as in one variable. Since det⁡(A±εI)=∏i(λi±ε)\det(\mat{A} \pm \eps\mat{I}) = \prod_i(\lambda_i \pm \eps), by the relationship between determinant and eigenvalues, both bounds converge to det⁡(A)\det(\mat{A}) as ε→0\eps \to 0.

∎

The geometric reading is direct: det⁡(−H)−1/2\det(-\mat{H})^{-1/2} is proportional to the volume of the uncertainty ellipsoid. A Hessian with eigenvalues λ1,…,λd\lambda_1, \dots, \lambda_d defines a Gaussian with standard deviations 1/nλi1/\sqrt{n\lambda_i} along eigendirections, and its mass is the product of the dd widths times (2π)d/2(2\pi)^{d/2}. A very flat direction (small eigenvalue) contributes much volume; a highly curved one, little.

Model evidence and BIC

Apply the theorem to the evidence. With θ^\hat\theta the posterior mode (MAP estimator) and Hn=∇2log⁡(p(D∣θ)p(θ))∣θ^\mat{H}_n = \hess\log\big(p(\Data \given \theta)p(\theta)\big)\big|_{\hat\theta},

log⁡Z=log⁡∫p(D∣θ) p(θ) ⁣dθ≈log⁡p(D∣θ^)+log⁡p(θ^)+d2log⁡(2π)−12log⁡det⁡(−Hn).\log Z = \log\int p(\Data \given \theta)\,p(\theta)\dd\theta \approx \log p(\Data \given \hat\theta) + \log p(\hat\theta) + \frac{d}{2}\log(2\pi) - \frac12\log\det(-\mat{H}_n).

This is the Laplace evidence, and the Gaussian N(θ^,(−Hn)−1)\Normal(\hat\theta, (-\mat{H}_n)\inv) producing it is the Laplace approximation of the posterior. With independent data, −Hn≈n J(θ^)-\mat{H}_n \approx n\,\mat{J}(\hat\theta), where J\mat{J} is Fisher information per observation, so log⁡det⁡(−Hn)=dlog⁡n+log⁡det⁡J+o(1)\log\det(-\mat{H}_n) = d\log n + \log\det\mat{J} + o(1) and

log⁡Z=log⁡p(D∣θ^)−d2log⁡n+O(1).\log Z = \log p(\Data \given \hat\theta) - \frac{d}{2}\log n + \bigO(1).

Removing bounded terms yields the BIC criterion: each parameter costs 12log⁡n\tfrac12\log n nats of evidence. You will implement it below with two-parameter logistic regression and verify that approximation error in log⁡Z\log Z falls like 1/n1/n.

Stirling’s formula

The method’s most famous example is the factorial. With the Gamma function, n!=Γ(n+1)=∫0∞xne−x ⁣dxn! = \Gamma(n + 1) = \int_0^\infty x^n e^{-x}\dd x, and the integrand enln⁡x−xe^{n\ln x - x} has its maximum at x=nx = n, which moves with nn. The change x=ntx = nt fixes it at t=1t = 1:

Γ(n+1)=nn+1∫0∞en(ln⁡t−t) ⁣dt.\Gamma(n + 1) = n^{n+1}\int_0^\infty e^{n(\ln t - t)}\dd t.

Now the exponent is nn times a fixed function, f(t)=ln⁡t−tf(t) = \ln t - t, with a unique maximum at t∗=1t^* = 1 with f(1)=−1f(1) = -1 and f′′(1)=−1f''(1) = -1. Laplace’s method gives ∫0∞en(ln⁡t−t) ⁣dt∼2π/n  e−n\int_0^\infty e^{n(\ln t - t)}\dd t \sim \sqrt{2\pi/n}\;e^{-n}, and multiplying by nn+1n^{n+1} yields Stirling’s formula:

You will prove the first part by checking the method’s assumptions in the guided exercise at the end. The second, with bounded remainder, is a classical result obtained using Euler–Maclaurin summation or Binet’s formula for ln⁡Γ\ln\Gamma (see de Bruijn’s book in the sources). The first terms are

ln⁡n!=nln⁡n−n+12ln⁡(2πn)+112n−1360n3+11260n5−11680n7+⋯\ln n! = n\ln n - n + \tfrac12\ln(2\pi n) + \frac{1}{12n} - \frac{1}{360n^3} + \frac{1}{1260n^5} - \frac{1}{1680n^7} + \cdots

Notice 1/(12n)1/(12n) is the c1c_1 calculated for f=ln⁡t−tf = \ln t - t: Laplace’s first correction reproduces Stirling’s first term, as it must, because e1/(12n)=1+1/(12n)+O(n−2)e^{1/(12n)} = 1 + 1/(12n) + \bigO(n^{-2}).

The accuracy is astonishing even for small nn. For 10!=3 628 80010! = 3\,628\,800, the leading term gives 3 598 695.63\,598\,695.6, relative error 0.83 %0.83\,\%. With correction 1/(12n)1/(12n) we obtain 3 628 810.053\,628\,810.05: error falls to 2.8×10−62.8\times 10^{-6}. In practice the useful form is logarithmic: ln⁡n!\ln n! for n=106n = 10^{6} is 1.28×1071.28\times 10^{7} nats, a number no computer writes as a factorial, but which nln⁡n−n+12ln⁡(2πn)n\ln n - n + \frac12\ln(2\pi n) gives to 13 correct digits.

When the leading term fails

The theorem’s assumptions are not decorative. Breaking each one changes the answer, and in each case there is a known correction. The opening figure has all three cases.

Maximum at the boundary. If x∗=ax^* = a is an interval endpoint, only half a Gaussian is integrated. There are two subcases:

  • If f′(a)=0f'(a) = 0 and f′′(a)<0f''(a) < 0, as in cos⁡x\cos x on [0,π)[0, \pi), the answer is half: ∫abenf∼122π/(n∣f′′(a)∣) enf(a)\int_a^b e^{nf} \sim \tfrac12\sqrt{2\pi/(n\abs{f''(a)})}\,e^{nf(a)}. Without factor 12\tfrac12, relative error tends to 100 %100\,\% instead of zero.
  • If f′(a)<0f'(a) < 0 (the function simply decreases from the boundary), the linear term dominates: f(x)≈f(a)+f′(a)(x−a)f(x) \approx f(a) + f'(a)(x - a) and ∫abenf∼enf(a)/(n∣f′(a)∣)\int_a^b e^{nf} \sim e^{nf(a)}/(n\abs{f'(a)}). Now the scale is 1/n1/n, not 1/n1/\sqrt n.

Multiple maxima. With several global maxima, each contributes its Gaussian and they are added. With a global maximum and another local one of height f∗−Δff^* - \Delta f with small Δf\Delta f, the theorem still holds, but the ratio of the two contributions is

pico secundariopico global≈e−n Δf∣fglobal′′∣∣fsecundario′′∣,\frac{\text{pico secundario}}{\text{pico global}} \approx e^{-n\,\Delta f}\sqrt{\frac{\abs{f''_{\text{global}}}}{\abs{f''_{\text{secundario}}}}},

which is small only when n Δfn\,\Delta f exceeds the logarithm of the curvature ratio. In the figure, Δf=0.067\Delta f = 0.067 and curvatures are 7.87.8 and 0.50.5: the broad peak wins until n≈20n \approx 20. For a multimodal posterior the consequence is serious: the Laplace approximation at the mode can miss most of the mass, and in high dimension the volume ratio is a product of dd factors.

Degenerate Hessian. If f′′(x∗)=0f''(x^*) = 0, the formula gives ∞\infty: the Gaussian would have infinite variance. The mass is then controlled by the first nonzero derivative. If f(x)≈f∗−c x2mf(x) \approx f^* - c\,x^{2m} near the maximum, with c>0c > 0, the change u=ncx2mu = ncx^{2m} and the definition of Γ\Gamma give

∫Re−nc x2m ⁣dx=Γ(1/(2m))m (nc)1/(2m),\int_\R e^{-nc\,x^{2m}}\dd x = \frac{\Gamma\big(1/(2m)\big)}{m\,(nc)^{1/(2m)}},

which decreases like n−1/(2m)n^{-1/(2m)}, more slowly than n−1/2n^{-1/2}. For m=2m = 2 and c=∣f(4)(x∗)∣/24c = \abs{f^{(4)}(x^*)}/24 this is the figure’s quartic correction. Its relative error falls only like n−1/2n^{-1/2}, not n−1n^{-1}. In the figure, f(x)=−(1−cos⁡x)2=−14x4+124x6+O(x8)f(x) = -(1 - \cos x)^2 = -\tfrac14x^4 + \tfrac1{24}x^6 + \bigO(x^8), and on the natural scale x=(4/n)1/4ux = (4/n)^{1/4}u the sixth-degree term is n x6/24=u6/(3n)n\,x^6/24 = u^6/(3\sqrt n): it is even, so does not vanish on integration, and its average against e−u4e^{-u^4} gives error −Γ(7/4)/(3 Γ(1/4)n)≈−0.0845/n-\Gamma(7/4)/(3\,\Gamma(1/4)\sqrt n) \approx -0.0845/\sqrt n, the reference line in the degenerate case.

Boundary note: singular models

In a regular model, the optimal parameter set is a point and the Hessian is nondegenerate. In neural networks, Gaussian mixtures or factor models, the set of parameters giving the same distribution is a variety with singularities (for example, if an output weight is zero, that neuron’s input weights are arbitrary), and the Hessian there is singular. The minimal example is f(x,y)=−x2y2f(x, y) = -x^2y^2 on [−1,1]2[-1, 1]^2: the maximum is the entire cross {xy=0}\{xy = 0\}, with no point at which to center a Gaussian.

Sumio Watanabe developed the theory replacing Laplace in this case using algebraic geometry’s resolution of singularities. Its central result says free energy (minus log evidence) behaves like

−log⁡Zn=n Ln(θ0)+λlog⁡n−(m−1)log⁡log⁡n+Op(1),-\log Z_n = n\,L_n(\theta_0) + \lambda\log n - (m - 1)\log\log n + \bigO_p(1),

where λ\lambda, the real log canonical threshold (or learning coefficient), and its multiplicity mm are geometric invariants of the singular set. In a regular model λ=d/2\lambda = d/2 and m=1m = 1, recovering BIC. In a singular one λ≤d/2\lambda \le d/2, often much smaller: the model is “simpler” than its parameter count suggests. For −x2y2-x^2y^2, λ=1/2\lambda = 1/2 and m=2m = 2, so Zn≍n−1/2log⁡nZ_n \asymp n^{-1/2}\log n replaces the n−1n^{-1} of a regular two-parameter model.

[ ]A singular maximum: the cross xy = 0Browser
import numpy as np
from scipy import integrate, special

def Z_singular(n):
    # ∫∫_{[-1,1]^2} exp(-n x^2 y^2): la integral en y es sqrt(pi/n)/|x| · erf(sqrt(n)|x|)
    interior = lambda x: np.sqrt(np.pi / n) * special.erf(np.sqrt(n) * x) / x if x > 0 else 2.0
    return 2 * integrate.quad(interior, 0, 1, points=[1 / np.sqrt(n)], limit=200)[0]

def Z_regular(n):
    # ∫∫_{[-1,1]^2} exp(-n (x^2 + y^2)) = (sqrt(pi/n) erf(sqrt(n)))^2
    return (np.sqrt(np.pi / n) * special.erf(np.sqrt(n))) ** 2

print("      n     Z regular   n·Z     Z singular   sqrt(n)·Z/log n")
for n in [1e2, 1e3, 1e4, 1e5, 1e6]:
    zr, zs = Z_regular(n), Z_singular(n)
    print(f"{n:9.0e}  {zr:.3e}  {n*zr:.4f}   {zs:.3e}     {np.sqrt(n)*zs/np.log(n):.4f}")

The regular case satisfies n Zn=πn\,Z_n = \pi to every printed digit, as Laplace predicts with d=2d = 2 (the difference is a Gaussian tail of order e−ne^{-n}). The singular case decays much more slowly: factor log⁡n\log n accompanying n−1/2n^{-1/2} is exactly Watanabe’s term −(m−1)log⁡log⁡n-(m - 1)\log\log n with m=2m = 2, seen in Zn=e−FnZ_n = e^{-F_n}. Column n Zn/log⁡n\sqrt{n}\,Z_n/\log n tends to π≈1.77\sqrt\pi \approx 1.77, but very slowly, because the next correction is relative order 1/log⁡n1/\log n (the free-energy term O(1)\bigO(1)). No adjustment to the Hessian fixes this; another theory is needed.

Logsumexp as a smooth maximum

The discrete version of Laplace’s method is the most used in machine learning. Given z∈Rn\vb{z} \in \R^n and τ>0\tau > 0, define

LSEτ(z)=τlog⁡∑i=1nezi/τ,softmax⁡τ(z)i=ezi/τ∑jezj/τ.\mathrm{LSE}_\tau(\vb{z}) = \tau\log\sum_{i=1}^n e^{z_i/\tau}, \qquad \softmax_\tau(\vb{z})_i = \frac{e^{z_i/\tau}}{\sum_j e^{z_j/\tau}}.

Here nn is the number of components, so the large parameter has a different name: with τ=1/s\tau = 1/s, the sum is ∑ieszi\sum_i e^{s z_i}, a Laplace “integral” over a finite set with s→∞s \to \infty, and the expectation is the same: the largest term dominates. Since there is no curvature to measure, what remains of the Gaussian is the number of indices tied at the maximum.

These five properties are what we call logsumexp as a smooth maximum. You will prove the bounds in point 1 in a guided exercise; the rest follow in a few lines.

Proof

(2) Factoring eM/τe^{M/\tau}, LSEτ(z)−M=τlog⁡(k+∑zi<Me−(M−zi)/τ)\mathrm{LSE}_\tau(\vb{z}) - M = \tau\log\big(k + \sum_{z_i < M}e^{-(M - z_i)/\tau}\big). Each term in the sum is at most e−Δ/τe^{-\Delta/\tau}, so τlog⁡k≤LSEτ−M≤τlog⁡k+τlog⁡(1+n−kke−Δ/τ)≤τlog⁡k+τn−kke−Δ/τ\tau\log k \le \mathrm{LSE}_\tau - M \le \tau\log k + \tau\log\big(1 + \tfrac{n-k}{k}e^{-\Delta/\tau}\big) \le \tau\log k + \tau\tfrac{n-k}{k}e^{-\Delta/\tau}, using log⁡(1+u)≤u\log(1 + u) \le u.

(3) Differentiating, ∂i τlog⁡∑jezj/τ=τ⋅ezi/τ/τ∑jezj/τ=pi\partial_i\,\tau\log\sum_j e^{z_j/\tau} = \tau\cdot\frac{e^{z_i/\tau}/\tau}{\sum_j e^{z_j/\tau}} = p_i. Differentiating again, ∂jpi=1τ(pi [i=j]−pipj)\partial_j p_i = \frac1\tau(p_i\,[i = j] - p_ip_j). For every v\vb{v}, v⊤(diag⁡p−pp⊤)v=∑ipivi2−(∑ipivi)2\vb{v}\T(\diag\vb{p} - \vb{p}\vb{p}\T)\vb{v} = \sum_i p_iv_i^2 - (\sum_i p_iv_i)^2, which is the variance of vIv_I with I∼pI \sim \vb{p} and therefore nonnegative.

(4) e(zi+c)/τ=ec/τezi/τe^{(z_i + c)/\tau} = e^{c/\tau}e^{z_i/\tau}: the factor leaves the logarithm as cc and cancels in the softmax quotient.

(5) Let p=softmax⁡τ(z)\vb{p} = \softmax_\tau(\vb{z}), so zi/τ=log⁡pi+LSEτ(z)/τz_i/\tau = \log p_i + \mathrm{LSE}_\tau(\vb{z})/\tau. For any q\vb{q} in the simplex,

⟨q,z⟩+τH(q)=τ∑iqi(ziτ−log⁡qi)=LSEτ(z)−τ∑iqilog⁡qipi=LSEτ(z)−τ KL⁡(q ∥ p).\inner{\vb{q}}{\vb{z}} + \tau H(\vb{q}) = \tau\sum_i q_i\Big(\frac{z_i}{\tau} - \log q_i\Big) = \mathrm{LSE}_\tau(\vb{z}) - \tau\sum_i q_i\log\frac{q_i}{p_i} = \mathrm{LSE}_\tau(\vb{z}) - \tau\,\KL(\vb{q} \,\|\, \vb{p}).

Since KL divergence is nonnegative and vanishes only if q=p\vb{q} = \vb{p}, the maximum is LSEτ(z)\mathrm{LSE}_\tau(\vb{z}) and is attained only at softmax.

∎
InteractiveSoftmax temperature
Logits ziz_i (drag them), maximum and smooth maximum
τ·LSE
softmax(z/τ)=∇z τ LSE(z/τ)\mathrm{softmax}(\vb{z}/\tau) = \nabla_{\vb{z}}\,\tau\,\mathrm{LSE}(\vb{z}/\tau)
0.410.180.080.020.301/n
Gap τ LSE(z/τ)−max⁡z\tau\,\mathrm{LSE}(\vb{z}/\tau) - \max\vb{z} versus τ\tau
  • gap
  • bound τ log n
  • logits
  • max⁡z\max\vb{z}
  • smooth maximum and band [max⁡,max⁡+τlog⁡n][\max, \max + \tau\log n]
  • numerical gradient
1.00
Smooth maximum τ LSE(z/τ)\tau\,\mathrm{LSE}(\vb{z}/\tau)2.8894
Gap and bound τlog⁡n\tau\log n0.889≤1.6090.889 \le 1.609
Entropy H(p)H(\vb{p}) (nats)1.326 of 1.609
⟨p,z⟩+τH(p)\langle\vb{p}, \vb{z}\rangle + \tau H(\vb{p})2.8894
Finite-difference gradient versus softmax: max⁡i∣∂i−pi∣=9.7⋅10−12\max_i |\partial_i - p_i| = 9.7\cdot 10^{-12}.
max⁡z=2.000≤2.889≤3.609=max⁡z+τlog⁡5\max \vb{z} = 2.000 \le 2.889 \le 3.609 = \max \vb{z} + \tau\log 5.
Drag the five logits and move temperature τ\tau. On the left, the magenta line is the smooth maximum τ LSE(z/τ)\tau\,\mathrm{LSE}(\vb{z}/\tau), always inside the shaded band between max⁡z\max\vb{z} and max⁡z+τlog⁡n\max\vb{z} + \tau\log n. On the right, softmax, exactly the gradient of the smooth maximum: points are that gradient calculated by finite differences. Below, the gap between smooth maximum and maximum, on log-log axes. Lower τ\tau with general logits and with a two-way tie: in one case the gap plummets, in the other it hugs τlog⁡2\tau\log 2. With ‘All equal’ the gap matches the bound. Mask a logit with −∞-\infty: its probability is exactly zero and nothing breaks.

The figure shows both regimes. As τ→0\tau \to 0, softmax tends to the uniform distribution over maximum indices (one-hot if unique) and the smooth maximum to the maximum. As τ→∞\tau \to \infty, softmax tends to uniform and LSEτ(z)−τlog⁡n→zˉ\mathrm{LSE}_\tau(\vb{z}) - \tau\log n \to \bar z, the mean of logits: expanding, log⁡1n∑iezi/τ=zˉ/τ+O(τ−2)\log\frac1n\sum_i e^{z_i/\tau} = \bar z/\tau + \bigO(\tau^{-2}). The identity in point 5 appears in the readouts: ⟨p,z⟩+τH(p)\inner{\vb{p}}{\vb{z}} + \tau H(\vb{p}) equals the smooth maximum for any z\vb{z} and τ\tau.

This structure appears throughout the curriculum:

  • Attention. The factor 1/dk1/\sqrt{d_k} in attention softmax is a temperature: without it, dot products grow like dk\sqrt{d_k} and softmax saturates toward the one-hot regime, where its Jacobian 1τ(diag⁡p−pp⊤)\frac1\tau(\diag\vb{p} - \vb{p}\vb{p}\T) is nearly zero and the gradient vanishes.
  • Sampling. An LLM’s temperature sampling rescales logits before softmax: τ<1\tau < 1 concentrates on the most likely tokens, τ>1\tau > 1 flattens.
  • Soft Bellman. In maximum-entropy RL, a state’s value is V(s)=τlog⁡∑aeQ(s,a)/τV(s) = \tau\log\sum_a e^{Q(s, a)/\tau} instead of max⁡aQ(s,a)\max_a Q(s, a), and the optimal policy is softmax: it is the variational form in point 5 applied at each state (soft Bellman equations).

Asymptotic series

Stirling’s formula with corrections has a puzzling property: the series ∑k≥1B2k/(2k(2k−1)n2k−1)\sum_{k \ge 1}B_{2k}/(2k(2k - 1)n^{2k-1}) diverges for every nn. Bernoulli numbers grow like ∣B2k∣∼2(2k)!/(2π)2k\abs{B_{2k}} \sim 2(2k)!/(2\pi)^{2k}, so term kk behaves like (2k−2)!/(2πn)2k(2k - 2)!/(2\pi n)^{2k} apart from slow factors, and the factorial eventually beats any power. Yet, as seen with 10!10!, the first terms are extraordinarily accurate. To understand this, separate two questions that go together in Taylor series.

The definition says nothing about what happens when more terms are summed with fixed xx; it only requires each truncation to be better than the preceding one in the limit. Convergence and asymptoticity look in perpendicular directions:

FixLet tendQuestion
ConvergencexxK→∞K \to \inftydoes the partial sum approach F(x)F(x)?
AsymptoticityKKx→x0x \to x_0is error smaller than the last term included?

Two immediate consequences. If it exists, the expansion is unique for a given sequence, because each coefficient is recovered as aK=lim⁡x→x0(F(x)−∑k<Kakφk(x))/φK(x)a_K = \lim_{x\to x_0}\big(F(x) - \sum_{k<K}a_k\varphi_k(x)\big)/\varphi_K(x). But the function is not determined by its expansion: e−1/x=o(xk)e^{-1/x} = o(x^k) for every kk as x→0+x \to 0^+, so FF and F+e−1/xF + e^{-1/x} have the same expansion in powers of xx. Exponentially small terms are invisible to a power series, and this is exactly what limits attainable accuracy.

Euler’s example

Proof

The finite geometric sum gives 11+xt=∑k=0K−1(−xt)k+(−xt)K1+xt\frac{1}{1 + xt} = \sum_{k=0}^{K-1}(-xt)^k + \frac{(-xt)^K}{1 + xt}. Integrating against e−te^{-t} and using ∫0∞tke−t ⁣dt=k!\int_0^\infty t^ke^{-t}\dd t = k!, the remainder is RK(x)=(−x)K∫0∞tKe−t1+xt ⁣dtR_K(x) = (-x)^K\int_0^\infty \frac{t^Ke^{-t}}{1 + xt}\dd t, and since 0<11+xt≤10 < \frac{1}{1 + xt} \le 1, ∣RK(x)∣≤xKK!\abs{R_K(x)} \le x^K K!. For fixed KK this is O(xK)=o(xK−1)\bigO(x^K) = o(x^{K-1}), the definition of asymptotic series. Divergence follows from the ratio test: ∣(k+1)!xk+1∣/∣k!xk∣=(k+1)x→∞\abs{(k+1)!x^{k+1}}/\abs{k!x^k} = (k + 1)x \to \infty.

∎

The error is smaller than the first omitted term, K! xKK!\,x^K. Those terms decrease while (k+1)x<1(k + 1)x < 1 and increase afterward, so it is best to truncate just before the smallest term, at K∗≈1/xK^* \approx 1/x. The resulting error is of order the smallest term, which by Stirling is K∗! xK∗≈2π/x  e−1/xK^*!\,x^{K^*} \approx \sqrt{2\pi/x}\;e^{-1/x}: exponentially small in 1/x1/x, the same scale as the earlier ambiguity e−1/xe^{-1/x}. This is optimal truncation, and the associated error cannot be improved with this series.

[ ]Euler’s series: divergent and usefulBrowser
import mpmath
mpmath.mp.dps = 40

x = mpmath.mpf("0.1")
E = mpmath.quad(lambda t: mpmath.e**(-t) / (1 + x * t), [0, mpmath.inf])
print("E(0.1) =", mpmath.nstr(E, 15))

suma, errores = mpmath.mpf(0), []
for K in range(0, 26):                       # K = número de términos sumados
    errores.append(abs(E - suma))
    suma += (-1)**K * mpmath.factorial(K) * x**K
for K in [0, 2, 5, 8, 10, 12, 15, 20, 25]:
    cota = mpmath.factorial(K) * x**K
    print(f"K = {K:2d}: error = {mpmath.nstr(errores[K], 3):>9s}   cota K!·x^K = {mpmath.nstr(cota, 3):>9s}")
K_opt = min(range(26), key=lambda K: errores[K])
print("truncamiento óptimo: K* =", K_opt, "  error mínimo =", mpmath.nstr(errores[K_opt], 3),
      "  sqrt(2π/x)·e^(-1/x) =", mpmath.nstr(mpmath.sqrt(2 * mpmath.pi / x) * mpmath.e**(-1 / x), 3))

With x=0.1x = 0.1, the optimum is at K∗=10K^* = 10 terms, with error 1.8×10−41.8\times 10^{-4}. With 25 terms error is already 0.440.44, almost half of E(0.1)≈0.916E(0.1) \approx 0.916 itself, and each new term multiplies it by more than 2.52.5. The bound K! xKK!\,x^K always holds, and actual error is a fraction of it, roughly half near the optimum, typical of alternating series of this kind.

Stirling, again

The same happens with Stirling’s series, with nn playing the role of 1/x1/x. Term kk is minimal near k≈πnk \approx \pi n, optimal error is of order e−2πn/(πn)e^{-2\pi n}/(\pi\sqrt n), and, as Stirling’s theorem says, the remainder has the sign of the first omitted term and is smaller than it: the series is called enveloping, because partial sums alternate above and below ln⁡n!\ln n!.

InteractiveStirling and the divergent series
Error with fixed n=1.00n = 1.00, more terms: K→∞K \to \infty
  • error after K terms
  • first omitted term
Error with fixed K=1K = 1, increasing nn: n→∞n \to \infty
  • error with K = 1
  • slope n⁻³
  • error with optimal K
Relative error of n!n! with K=1K = 1: +0.00227+0.00227. Errors were calculated to 90 digits: in float64 they could not go below 10−1610^{-16}.
1.00
1
ln⁡n!≈nln⁡n−n+12ln⁡(2πn)+112n\ln n! \approx n\ln n - n + \tfrac12\ln(2\pi n) + \frac{1}{12n}
n!=Γ(n+1)n! = \Gamma(n + 1)1.0000001.000000
Stirling S1(n)S_{1}(n)1.0022721.002272
Error ∣ln⁡SK−ln⁡n!∣|\ln S_K - \ln n!|2.27⋅10−32.27\cdot 10^{-3}
Omitted term ∣t2∣|t_{2}|2.78⋅10−32.78\cdot 10^{-3}
Optimal K∗K^* for this nn3
Smallest attainable error2.9⋅10−42.9\cdot 10^{-4}
Before optimal truncation: terms still decrease, ∣t2∣=2.8⋅10−3<∣t1∣=0.083|t_{2}| = 2.8\cdot 10^{-3} < |t_{1}| = 0.083, and adding the next improves the approximation.
On the left, with fixed nn, error ∣ln⁡SK(n)−ln⁡n!∣\abs{\ln S_K(n) - \ln n!} after KK correction terms (orange) and the first omitted term (gray): error always stays below. With n=1n = 1, add terms one by one: error drops to K∗=3K^* = 3 then rises without bound. Repeat with n=3n = 3 and n=10n = 10: the optimum moves toward K∗≈πnK^* \approx \pi n and minimum error reaches 10−2910^{-29}. On the right, with fixed KK, error versus nn: each truncation falls like n−(2K+1)n^{-(2K+1)} and is an excellent asymptotic approximation. The two graphs are the two questions in the table.

The practical lesson is the same as for asymptotic expansions in combinatorics: in an asymptotic series, “more terms” does not mean “more accuracy.” For large nn, two or three terms give more digits than needed; for small nn, there is a limit no number of terms surpasses, and the correct use is to truncate at the smallest term. Beyond optimal truncation there are techniques (Borel resummation, hyperasymptotics) recovering the exponentially small part, but these are specialist asymptotic analysis.

Implementation from scratch

First, Laplace’s method in one variable with Newton for the mode. The example is evidence for a coin with uniform prior: with kk heads in nn tosses, Z=∫01θk(1−θ)n−k ⁣dθ=B(k+1,n−k+1)Z = \int_0^1 \theta^k(1 - \theta)^{n-k}\dd\theta = B(k + 1, n - k + 1), which has closed form and allows exact error measurement. We also compare approximation in the original variable θ\theta with approximation in logit variable u=log⁡θ1−θu = \log\frac{\theta}{1-\theta}, in which the integrand becomes θk+1(1−θ)n−k+1\theta^{k+1}(1 - \theta)^{n-k+1} due to Jacobian  ⁣dθ=θ(1−θ) ⁣du\dd\theta = \theta(1 - \theta)\dd u.

[ ]Laplace in one variable: evidence for a coinBrowser
import numpy as np
from math import lgamma, log, pi

def newton_1d(d1, d2, x0, tol=1e-12, max_iter=50):
    """Máximo de log f por Newton: x <- x - f'(x)/f''(x)."""
    x = x0
    for _ in range(max_iter):
        paso = d1(x) / d2(x)
        x -= paso
        if abs(paso) < tol:
            break
    return x

def laplace_logZ_1d(logf, d1, d2, x0):
    """log ∫ f ≈ log f(x*) + ½ log(2π / |(log f)''(x*)|)."""
    xs = newton_1d(d1, d2, x0)
    A = -d2(xs)
    assert A > 0, "el máximo debe ser no degenerado"
    return logf(xs) + 0.5 * log(2 * pi / A)

sig = lambda u: 1 / (1 + np.exp(-u))
print("    n    k   log Z exacto   error en θ   n·error   error en logit   n·error")
for n in [10, 20, 50, 100, 200, 500, 1000]:
    k = round(0.3 * n)
    exacto = lgamma(k + 1) + lgamma(n - k + 1) - lgamma(n + 2)       # log B(k+1, n-k+1)
    en_theta = laplace_logZ_1d(lambda t: k * np.log(t) + (n - k) * np.log1p(-t),
                               lambda t: k / t - (n - k) / (1 - t),
                               lambda t: -k / t**2 - (n - k) / (1 - t)**2, 0.5)
    en_logit = laplace_logZ_1d(lambda u: (k + 1) * np.log(sig(u)) + (n - k + 1) * np.log(sig(-u)),
                               lambda u: (k + 1) * sig(-u) - (n - k + 1) * sig(u),
                               lambda u: -(n + 2) * sig(u) * sig(-u), 0.0)
    e1, e2 = np.expm1(en_theta - exacto), np.expm1(en_logit - exacto)
    print(f"{n:5d} {k:4d}  {exacto:12.4f}    {e1:+.2e}   {n*e1:+.3f}     {e2:+.2e}      {n*e2:+.3f}")

The two n⋅n\cdoterror columns stabilize: relative error is O(1/n)\bigO(1/n), as the theorem says. But constants differ, +0.686+0.686 in θ\theta and −0.313-0.313 in the logit variable. The Laplace approximation is not invariant under reparameterization: the Jacobian changes the integrand, and with it the mode and curvature. In θ∈(0,1)\theta \in (0, 1) the integrand is asymmetric and close to a boundary; in u∈Ru \in \R it is more symmetric and Gaussian-like, and error is reduced by more than half. Choosing the parameterization in which the posterior is more Gaussian is a modeling decision, not a detail.

Now the two-variable case: evidence for Bayesian logistic regression with slope and bias, w=(w,b)\vb{w} = (w, b), prior N(0,4 I)\Normal(\vb{0}, 4\,\mat{I}) and unnormalized log posterior

log⁡p(D∣w)+log⁡p(w)=∑i=1n(yi xi⊤w−log⁡(1+exi⊤w))−∥w∥28−log⁡(8π).\log p(\Data \given \vb{w}) + \log p(\vb{w}) = \sum_{i=1}^n \big(y_i\,\vb{x}_i\T\vb{w} - \log(1 + e^{\vb{x}_i\T\vb{w}})\big) - \frac{\norm{\vb{w}}^2}{8} - \log(8\pi).

Its gradient is X⊤(y−p)−w/4\mat{X}\T(\vb{y} - \vb{p}) - \vb{w}/4 and Hessian −X⊤diag⁡(p⊙(1−p))X−I/4-\mat{X}\T\diag\big(\vb{p}\odot(1 - \vb{p})\big)\mat{X} - \mat{I}/4, with p=σ(Xw)\vb{p} = \sigmoid(\mat{X}\vb{w}): always negative definite, thanks to the prior. The reference is quadrature on a grid of 61×6161\times 61 points in whitened coordinates w=w^+Lu\vb{w} = \hat{\vb{w}} + \mat{L}\vb{u}, with LL⊤=(−H)−1\mat{L}\mat{L}\T = (-\mat{H})\inv, where the integrand is nearly standard Gaussian and the trapezoid rule converges very quickly.

[ ]Laplace in two variables: Bayesian logistic regressionBrowser
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(0)
w_real = np.array([1.5, -0.5])                         # pendiente y sesgo
X_todo = np.column_stack([rng.normal(size=640), np.ones(640)])
y_todo = (rng.random(640) < sig(X_todo @ w_real)).astype(float)
s2 = 4.0                                                # varianza del prior

def log_post(W, X, y):
    """Log-posterior no normalizada en cada fila de W (forma (m, 2))."""
    W = np.atleast_2d(W)
    Z = X @ W.T
    return y @ Z - np.logaddexp(0, Z).sum(axis=0) - (W**2).sum(axis=1) / (2 * s2) - np.log(2 * np.pi * s2)

def grad_hess(w, X, y):
    p = sig(X @ w)
    g = X.T @ (y - p) - w / s2
    H = -(X.T * (p * (1 - p))) @ X - np.eye(2) / s2
    return g, H

def moda_newton(X, y, tol=1e-10):
    w = np.zeros(2)
    for it in range(50):
        g, H = grad_hess(w, X, y)
        paso = np.linalg.solve(H, g)
        w = w - paso
        if np.linalg.norm(paso) < tol:
            break
    return w, grad_hess(w, X, y)[1], it + 1

def laplace_logZ(X, y):
    w, H, its = moda_newton(X, y)
    signo, logdet = np.linalg.slogdet(-H)
    assert signo > 0, "el hessiano debe ser definido negativo"
    d = len(w)
    return log_post(w, X, y)[0] + 0.5 * d * np.log(2 * np.pi) - 0.5 * logdet, w, H, its

def cuadratura_logZ(X, y, w, H, m=61, R=7.0):
    L = np.linalg.cholesky(np.linalg.inv(-H))           # w = w* + L u
    u = np.linspace(-R, R, m)
    U = np.stack(np.meshgrid(u, u), -1).reshape(-1, 2)
    lp = log_post(w + U @ L.T, X, y)
    c = lp.max()
    peso = np.ones(m); peso[[0, -1]] = 0.5               # regla del trapecio
    P = np.outer(peso, peso).ravel()
    h = u[1] - u[0]
    return c + np.log(np.sum(P * np.exp(lp - c)) * h * h) + np.log(np.linalg.det(L))

ns, errores = [10, 20, 40, 80, 160, 320, 640], []
print("    n  iter. Newton   log Z (cuadratura)   log Z (Laplace)    error     n·error")
for n in ns:
    X, y = X_todo[:n], y_todo[:n]
    lz, w, H, its = laplace_logZ(X, y)
    q = cuadratura_logZ(X, y, w, H)
    errores.append(lz - q)
    print(f"{n:5d}      {its}         {q:13.6f}       {lz:13.6f}     {lz - q:+.2e}   {n * (lz - q):+.3f}")

w, H, _ = moda_newton(X_todo[:10], y_todo[:10])
fina = cuadratura_logZ(X_todo[:10], y_todo[:10], w, H, m=101, R=9.0)
print("comprobación de la cuadratura con n = 10 (malla 101x101):",
      f"{abs(fina - cuadratura_logZ(X_todo[:10], y_todo[:10], w, H)):.1e}")

plt.loglog(ns, np.abs(errores), "o-", label="|log Z Laplace − log Z cuadratura|")
plt.loglog(ns, 1.6 / np.array(ns), "--", color="gray", label="1.6 / n")
plt.xlabel("número de datos n"); plt.ylabel("error en log Z"); plt.legend(); plt.show()

Newton converges in 5 or 6 iterations in every case (the log posterior is concave), and error in log⁡Z\log Z falls like 1/n1/n, with n⋅n\cdoterror stabilizing around −1.6-1.6 from n=80n = 80 onward (the sample is the same enlarged, so the constant still oscillates somewhat with the data). Quadrature, with error at most 10−610^{-6}, is a reliable reference. In two dimensions that grid costs 37213721 likelihood evaluations; in d=20d = 20, the same resolution would require 6120≈5×103561^{20} \approx 5\times 10^{35}. Laplace costs one Newton fit plus a determinant, in any dimension: this is why it is the default approximation when dd is large and the posterior unimodal.

Finally, stable logsumexp and softmax. Naive and stable versions are compared with normal, large and very negative logits and with −∞-\infty (a masked token).

[ ]Stable logsumexp and softmax from scratchBrowser
import numpy as np

def logsumexp_ingenuo(z):
    return np.log(np.sum(np.exp(z)))

def logsumexp_estable(z, tau=1.0):
    z = np.asarray(z, dtype=float) / tau
    M = np.max(z)
    if np.isneginf(M):                     # todos son -inf: la suma vacía
        return -np.inf
    return tau * (M + np.log(np.sum(np.exp(z - M))))

def softmax_estable(z, tau=1.0):
    z = np.asarray(z, dtype=float) / tau
    e = np.exp(z - np.max(z))
    return e / e.sum()

casos = {"normales": [2.0, 1.0, 0.5], "grandes": [1000.0, 999.0, 0.0],
         "negativos": [-1000.0, -1001.0, -2000.0], "con -inf": [3.0, -np.inf, 1.0]}
with np.errstate(over="ignore", divide="ignore", invalid="ignore"):
    for nombre, z in casos.items():
        print(f"{nombre:10s} ingenuo = {logsumexp_ingenuo(np.array(z)):>10.4f}   "
              f"estable = {logsumexp_estable(z):>10.4f}   softmax = {np.round(softmax_estable(z), 4)}")

z = np.array([2.0, 1.2, 0.3, -0.8, 1.7])
print()
for tau in [10.0, 1.0, 0.1, 0.01]:
    S = logsumexp_estable(z, tau)
    print(f"tau = {tau:5}:  max = {z.max():.4f} <= {S:.6f} <= {z.max() + tau * np.log(len(z)):.4f}")

h = 1e-6
grad = np.array([(logsumexp_estable(z + h * e) - logsumexp_estable(z - h * e)) / (2 * h) for e in np.eye(len(z))])
print("\nmáx |gradiente numérico − softmax| =", np.abs(grad - softmax_estable(z)).max())

The naive version returns inf with logits 10001000 and -inf with logits −1000-1000; the stable one gives 1000.31331000.3133 and −999.6867-999.6867. With τ=0.1\tau = 0.1 the gap is already only 0.00490.0049, and with τ=0.01\tau = 0.01 the smooth maximum equals the maximum to every printed digit: the term τe−Δ/τ\tau e^{-\Delta/\tau} with Δ=0.3\Delta = 0.3 there is 0.01 e−30≈10−150.01\,e^{-30} \approx 10^{-15}.

The professional version

ToolPurpose
scipy.special.gammaln(x)ln⁡Γ(x)\ln\Gamma(x) without overflow; gammaln(n + 1) is ln⁡n!\ln n!
scipy.special.logsumexp(z, axis, b=None)stable logsumexp over axes, with optional weights bib_i
scipy.special.softmax(z, axis)stable softmax over axes
scipy.optimize.minimize(fun, x0, jac, method)the mode, minimizing the negated log posterior
mpmatharbitrary-precision arithmetic to check asymptotics
torch.logsumexp, torch.softmaxthe same in PyTorch, with automatic differentiation
[ ]Gamma, Stirling and logsumexp with SciPyBrowser
import numpy as np
import mpmath
from scipy.special import gammaln, logsumexp, softmax
from scipy.optimize import minimize

# Stirling con K correcciones frente a mpmath con 50 cifras
mpmath.mp.dps = 50
def stirling_ln(n, K):
    n = mpmath.mpf(n)
    s = n * mpmath.log(n) - n + mpmath.log(2 * mpmath.pi * n) / 2
    for k in range(1, K + 1):
        s += mpmath.bernoulli(2 * k) / (2 * k * (2 * k - 1) * n**(2 * k - 1))
    return s

print("   n        gammaln(n+1)      error K=0   K=1        K=2        K=4")
for n in [1, 5, 10, 100]:
    exacto = mpmath.loggamma(n + 1)
    errs = [float(abs(stirling_ln(n, K) - exacto)) for K in (0, 1, 2, 4)]
    print(f"{n:4d}  {gammaln(n + 1):18.12f}   " + "  ".join(f"{e:.2e}" for e in errs))
print("ln(10^6 !) =", gammaln(1e6 + 1), "  Stirling K=0:", float(stirling_ln(10**6, 0)))

# logsumexp y softmax por ejes, comparados con lo implementado arriba
Zl = np.array([[1000.0, 999.0, 0.0], [-1000.0, -1001.0, -2000.0], [3.0, -np.inf, 1.0]])
print("\nscipy logsumexp por filas:", logsumexp(Zl, axis=1))
print("propio:                   ", [logsumexp_estable(fila) for fila in Zl])
print("softmax por filas:\n", np.round(softmax(Zl, axis=1), 4))

# la moda de la regresión logística con BFGS frente a Newton
X, y = X_todo[:80], y_todo[:80]
res = minimize(lambda w: -log_post(w, X, y)[0], np.zeros(2),
               jac=lambda w: -grad_hess(w, X, y)[0], method="BFGS")
w_newton, H, _ = moda_newton(X, y)
print("\nmoda BFGS:", np.round(res.x, 6), " moda Newton:", np.round(w_newton, 6), " evaluaciones:", res.nfev)
cov_exacta = np.linalg.inv(-H)
print("hess_inv de BFGS:\n", np.round(res.hess_inv, 4))
print("(-H)^-1 exacta:\n", np.round(cov_exacta, 4))
print("error relativo de hess_inv:", np.linalg.norm(res.hess_inv - cov_exacta) / np.linalg.norm(cov_exacta))

gammaln agrees with mpmath.loggamma to float64 precision, and the error table reproduces the figure: for n=100n = 100, two corrections already go below 10−1210^{-12}. For 106!10^6!, Stirling’s leading term and gammaln differ by 8.2×10−88.2\times 10^{-8} over 1.28×1071.28\times 10^{7}: exactly the first correction, 1/(12⋅106)=8.3×10−81/(12\cdot 10^6) = 8.3\times 10^{-8}, at float64 rounding level. scipy.special.logsumexp handles the same extreme cases as our version, including rows with −∞-\infty.

The last part deserves a warning. minimize with BFGS finds the mode, but its hess_inv approximates the inverse Hessian using the few directions explored by the optimizer; it is not the Hessian at the mode. Laplace requires the actual Hessian: analytic, by automatic differentiation (in PyTorch, torch.func.hessian) or by finite differences of the gradient.

Common mistakes

Exercises

NumericStirling for 10!
Calculate the relative error 1−S/10!1 - S/10! of the Stirling approximation S=2π⋅10 (10/e)10S = \sqrt{2\pi\cdot 10}\,(10/e)^{10} against 10!=3 628 80010! = 3\,628\,800.
NumericLaplace for cosine
The integral ∫−ππe50cos⁡x ⁣dx\int_{-\pi}^{\pi} e^{50\cos x}\dd x is exactly 2πI0(50)2\pi I_0(50). Calculate the ratio between the Laplace approximation and that exact value.
NumericThe gap with a tie
With z=(2,2,0.5)\vb{z} = (2, 2, 0.5) and τ=0.1\tau = 0.1, calculate τ LSE(z/τ)−max⁡z\tau\,\mathrm{LSE}(\vb{z}/\tau) - \max\vb{z}.
NumericOptimal truncation
For E(x)=∫0∞e−t/(1+xt) ⁣dtE(x) = \int_0^\infty e^{-t}/(1 + xt)\dd t with x=0.07x = 0.07, how many terms of series ∑k(−1)kk! xk\sum_k (-1)^k k!\,x^k (starting at k=0k = 0) should be summed to minimize error?
QuizWhen does the leading term fail?
Let I(n)=∫enf(x) ⁣dxI(n) = \int e^{nf(x)}\dd x. In which situations is the standard leading term 2π/(n∣f′′(x∗)∣) enf(x∗)\sqrt{2\pi/(n\abs{f''(x^*)})}\,e^{nf(x^*)}, calculated at a global maximum x∗x^*, not asymptotically equivalent to I(n)I(n)?

More than one answer may be correct.

QuizWhat an asymptotic series does and does not say
Which statements are true?

More than one answer may be correct.

ProofStirling from the Gamma function
Prove: n!∼2πn (n/e)nn! \sim \sqrt{2\pi n}\,(n/e)^n as n→∞n \to \infty.
0
Start from n!=Γ(n+1)=∫0∞xne−x ⁣dx=∫0∞enln⁡x−x ⁣dxn! = \Gamma(n + 1) = \int_0^\infty x^n e^{-x}\dd x = \int_0^\infty e^{n\ln x - x}\dd x.

Step 1 of 4. The maximum of exponent nln⁡x−xn\ln x - x is at x=nx = n and moves with nn. What do you do?

ProofBounds on the smooth maximum
Prove: For z∈Rn\vb{z} \in \R^n and τ>0\tau > 0, max⁡izi≤τlog⁡∑i=1nezi/τ≤max⁡izi+τlog⁡n\max_i z_i \le \tau\log\sum_{i=1}^n e^{z_i/\tau} \le \max_i z_i + \tau\log n.
0
Call M=max⁡iziM = \max_i z_i and let jj be an index with zj=Mz_j = M.

Step 1 of 3. How do you start?

CodeLogsumexp and softmax over axes
Implement stable logsumexp(z, axis=-1) and softmax(z, axis=-1) for NumPy arrays of any shape. logsumexp removes axis axis; softmax preserves shape and its values sum to 1 along axis. They must handle logits ±1000\pm 1000 without warnings or infinities, accept −∞-\infty inputs (which give probability 0) and, if all entries of a row are −∞-\infty, logsumexp must return −∞-\infty for that row. Do not use scipy.special.
import numpy as np

def logsumexp(z, axis=-1):
  z = np.asarray(z, dtype=float)
  return np.log(np.sum(np.exp(z), axis=axis))

def softmax(z, axis=-1):
  z = np.asarray(z, dtype=float)
  e = np.exp(z)
  return e / np.sum(e, axis=axis, keepdims=True)
Shift+Enter to run

Summary

Key idea
When a large exponent multiplies a function, all the mass of ∫enf\int e^{nf} concentrates in a window of width 1/n1/\sqrt{n} around the maximum, where ff is a parabola: the integral becomes Gaussian, 2π/(n∣f′′∣) enf∗\sqrt{2\pi/(n\abs{f''})}\,e^{nf^*}, with relative error O(1/n)\bigO(1/n).
  • Laplace’s method needs a unique, interior, separated and nondegenerate maximum. In Rd\R^d the factor is (2π/n)d/2det⁡(−H)−1/2(2\pi/n)^{d/2}\det(-\mat{H})^{-1/2}, proportional to the uncertainty ellipsoid’s volume; applied to model evidence, it gives the Laplace approximation of the posterior and BIC.
  • The first correction is 1+c1/n1 + c_1/n with c1=f4/(8A2)+5f32/(24A3)c_1 = f_4/(8A^2) + 5f_3^2/(24A^3). Applied to Γ(n+1)\Gamma(n + 1) after x=ntx = nt, it gives Stirling’s formula and first correction 1/(12n)1/(12n).
  • The leading term fails at the boundary (factor 1/21/2, or scale 1/n1/n if f′≠0f' \neq 0), with multiple comparable maxima (sum them), and with a degenerate Hessian (scale n−1/(2m)n^{-1/(2m)}). In singular models such as neural networks, Watanabe’s theory replaces d/2d/2 with a coefficient λ≤d/2\lambda \le d/2.
  • τ LSE(z/τ)\tau\,\mathrm{LSE}(\vb{z}/\tau) is a smooth maximum: between max⁡z\max\vb{z} and max⁡z+τlog⁡n\max\vb{z} + \tau\log n, convex, its gradient is softmax, and it is the maximum of ⟨q,z⟩+τH(q)\inner{\vb{q}}{\vb{z}} + \tau H(\vb{q}) on the simplex. Always compute it by subtracting the maximum.
  • An asymptotic series improves each truncation as n→∞n \to \infty, but with fixed nn it can diverge: Euler’s and Stirling’s do. Truncate before the smallest term, and the remaining error is of that order, exponentially small in nn.