Module contents
Stage 1 of 9Advanced 90 min

2D diffusion with a known score

Build and inspect a complete 2D diffusion system, using the exact score of a Gaussian mixture to diagnose the network, samplers and generated samples.

After this lesson you can

  • Implement the forward-process marginal and noise-prediction loss.
  • Derive the exact score of a noisy Gaussian mixture and use it as a reference.
  • Compare learned and exact scores by noise level and region.
  • Sample with exact and learned scores and quantify discrepancies using MMD.

Before you start

A generator we can inspect

An image diffusion model has three pieces that can fail at once: the network that estimates the score, the integrator that runs time backward, and the metric used to judge the samples. When an image is blurry, we cannot directly tell which piece is responsible because we do not know the true score of the image distribution. In two dimensions we can. If the data form a Gaussian mixture, the noisy distribution at every time is another Gaussian mixture with a closed-form score. This exact score is an oracle: a correct answer against which to measure each piece separately.

We will build the complete system in the plane with NumPy: the closed-form forward process, a small network with backpropagation written by hand, the noise-prediction loss, three samplers (reverse SDE, probability-flow ODE, and DDPM ancestral step), and the MMD sample metric. Each piece is checked against the oracle. The result will be a numerical diagnosis of network error at each noise level and in each region, integrator error, and the specific bias in the samples.

The first interactive shows the central phenomenon. It plots the exact score in blue and the score of the network trained in this lesson’s lab in pink, over a background colored by their discrepancy. Start at t=0.02t=0.02, a low noise level. The density-weighted relative error ptp_t is 0.207, while uniform measurement over the square [−3,3]2[-3,3]^2 gives 0.290. The discrepancy is concentrated between modes, near the origin and in the corners, where little probability mass lies. The marked point (1.2,0.8)(1.2,0.8) is on the side of the +x1+x_1 mode facing the gap. The exact score (2.58,−3.27)(2.58,-3.27) pushes strongly toward that mode. The network points in nearly the same direction but at less than half the length, (0.84,−1.61)(0.84,-1.61), giving a local discrepancy of 0.83 times the score RMS. Now click (1,1)(1,1) on the diagonal. A saddle point of ptp_t lies very nearby: both scores are short and differ in direction by about 33∘33^\circ, but the absolute discrepancy is small (0.12). Between modes, the main error is the magnitude on slopes descending toward the gap. Then raise tt to 0.20.2. Both errors fall to 0.07 and become equal because noise has filled the gap between modes.

InteractiveTwo fields for the same density
−33−33x₁x₂
  • Exact score
  • Network score
  • Discrepancy |s_θ − s| (clipped at the RMS of s)
  • Components: one-standard-deviation circle
Field
Background
0.02
a(t)0.852
Relative error weighted by p_t0.207
Uniform relative error on [−3, 3]²0.290
Exact at (1.20, 0.80)(2.58, −3.27)
Network at the same point(0.84, −1.61)
Local discrepancy / RMS0.83
Time controls the noisy distribution ptp_t. The exact field uses the mixture formula; the learned field uses the lab network and its weights. Arrow lengths saturate for readability. The background can show the discrepancy ∥sθ−s∥\norm{s_\theta-s} or the density. Dashed circles have radius one component standard deviation.

The toy process

This is an Ornstein–Uhlenbeck process, so its law conditioned on X0X_0 is available without numerical integration. Its mean m(t)=E[Xt∣X0]m(t)=\E[X_t\given X_0] satisfies m′=−4mm'=-4m, hence m(t)=e−4tX0m(t)=e^{-4t}X_0. The variance per coordinate v(t)v(t) satisfies v′=−8v+8v'=-8v+8 with v(0)=0v(0)=0, hence v(t)=1−e−8tv(t)=1-e^{-8t}. Writing a(t)=e−8ta(t)=e^{-8t},

Xt=a(t) X0+1−a(t) ε,ε∼N(0,I), ε⊥X0.X_t=\sqrt{a(t)}\,X_0+\sqrt{1-a(t)}\,\varepsilon,\qquad \varepsilon\sim\Normal(\vb 0,\mat I),\ \varepsilon\perp X_0 .

The plane’s units are arbitrary, and the mixture is a constructed test distribution. Its advantage is that its density is known at every time. Two boundary details matter throughout. First, a(1)=e−8≈3.4×10−4a(1)=e^{-8}\approx 3.4\times10^{-4}, so p1p_1 is very close to N(0,I)\Normal(\vb 0,\mat I) but does not equal it. Second, the network is trained only for t≥tmin⁡=0.002t\ge t_{\min}=0.002 because converting predicted noise to a score divides by 1−a(t)\sqrt{1-a(t)}, which vanishes at t=0t=0. The samplers stop at tmin⁡t_{\min}, where each mode has standard deviation 1−a+0.09a≈0.323\sqrt{1-a+0.09a}\approx0.323 per coordinate instead of 0.30.3.

Signal, noise and mode separation

The process’s conventional signal-to-noise ratio (SNR) is

SNR⁡(t)=a(t)1−a(t)=1e8t−1:\operatorname{SNR}(t)=\frac{a(t)}{1-a(t)}=\frac{1}{e^{8t}-1}:

It compares the squared signal multiplier with the added noise variance. It equals 1 at t=ln⁡2/8≈0.087t=\ln2/8\approx0.087 and decreases monotonically. It is the variance ratio only when the data have unit variance per coordinate. Here Var⁡(X0,1)=14(4+4+0+0)+0.09=2.09\operatorname{Var}(X_{0,1})=\tfrac14(4+4+0+0)+0.09=2.09, so the actual variance ratio is 2.09 SNR⁡(t)2.09\,\operatorname{SNR}(t).

For a mixture, a different quantity determines the behavior: the distance between neighboring component means measured in component standard deviations. The means of (2,0)(2,0) and (0,2)(0,2) are 22a2\sqrt2\sqrt a apart, and each component has standard deviation 1−a+0.09a\sqrt{1-a+0.09a}. The ratio is 3.71 at t=0.05t=0.05, 2.47 at t=0.1t=0.1, 1.41 at t=0.2t=0.2, and 0.89 at t=0.3t=0.3. Between t≈0.1t\approx0.1 and t≈0.3t\approx0.3 the four modes merge into one cloud. In reverse, that interval is where sampling decides which mode each particle reaches. Score error there changes the modes’ weights rather than their shapes. We will return to this observation.

NumericThe time of unit SNR
Given a(t)=e−8ta(t)=e^{-8t}, at what time tt is the signal-to-noise ratio a/(1−a)a/(1-a) equal to 1?

From the SDE to discrete steps

The DDPM of Ho and colleagues works in discrete time: each step multiplies by αi\sqrt{\alpha_i} and adds independent Gaussian noise of variance 1−αi1-\alpha_i, yielding a forward process whose marginal has a closed form with αˉi=∏j≤iαj\bar\alpha_i=\prod_{j\le i}\alpha_j. If we divide [0,1][0,1] into steps of length Δ\Delta and take αi=a(iΔ)/a((i−1)Δ)=e−8Δ\alpha_i=a(i\Delta)/a((i-1)\Delta)=e^{-8\Delta}, the telescoping product gives αˉi=a(iΔ)\bar\alpha_i=a(i\Delta) exactly. The discrete chain therefore has the same marginals as the SDE at the grid points. Also 1−αi=1−e−8Δ≈8Δ1-\alpha_i=1-e^{-8\Delta}\approx8\Delta, so discrete βi\beta_i is the continuous rate times the step length.

ProofThe closed-form marginal
Prove: In the discrete process, X_i = √α_i X_{i−1} + √(1−α_i) ε_i, with α_i in (0,1), standard normal noises ε_i independent of one another and of X_0, and ᾱ_i = α_1⋯α_i. Prove that X_i given X_0 = x₀ is normal with mean √ᾱ_i x₀ and covariance (1−ᾱ_i) I.
0
The case i = 1 is the definition itself. Suppose the formula holds for i − 1 and write X_{i−1} = √ᾱ_{i−1} x₀ + √(1−ᾱ_{i−1}) ε̄, where ε̄ is standard normal and independent of ε_i.

Step 1 of 3. Why is X_i given x₀ still Gaussian?

The first cell defines the mixture, sampling from ptp_t, and the exact score, then checks it against finite differences of the log density. The second follows the discrete chain step by step and checks whether its moments agree with the closed form.

[ ]Mixture and exact scoreBrowser
import numpy as np

means = np.array([[2.,0.],[-2.,0.],[0.,2.],[0.,-2.]])
sigma0 = .3
beta = 8.0
t_min = .002

def sample_data(n, rng):
    return means[rng.integers(0,len(means),n)] + sigma0*rng.standard_normal((n,2))

def alpha_bar(t):
    return np.exp(-beta*np.asarray(t))

def noisy_sample(n, t, rng):
    a = alpha_bar(t)
    return np.sqrt(a)*sample_data(n,rng) + np.sqrt(1-a)*rng.standard_normal((n,2))

def exact_score(x,t):
    x = np.asarray(x)
    a = alpha_bar(t)
    variance = 1-a + a*sigma0**2
    delta = x[:,None,:] - np.sqrt(a)*means[None,:,:]
    logits = -(delta**2).sum(axis=-1)/(2*variance)
    responsibility = np.exp(logits-logits.max(axis=1,keepdims=True))
    responsibility /= responsibility.sum(axis=1,keepdims=True)
    return -(responsibility[:,:,None]*delta).sum(axis=1)/variance

def log_density(x,t):
    a = alpha_bar(t)
    variance = 1-a+a*sigma0**2
    delta = x[:,None,:]-np.sqrt(a)*means
    logits = -(delta**2).sum(axis=-1)/(2*variance)
    m = logits.max(axis=1,keepdims=True)
    return (m[:,0]+np.log(np.exp(logits-m).mean(axis=1))
            -np.log(2*np.pi*variance))

points = np.array([[.4,-.8],[1.5,.2],[-1.,1.]])
for t in (.01,.2,1.):
    h = 1e-5
    numerical = np.column_stack([
        (log_density(points+np.eye(2)[j]*h,t)-log_density(points-np.eye(2)[j]*h,t))/(2*h)
        for j in range(2)])
    error = np.max(np.abs(numerical-exact_score(points,t)))
    assert error < 1e-7
    print("t =",t,"error máximo de diferencias finitas:",error)
print("a(1) =",alpha_bar(1.0),"varianza de cada modo en t=0:",sigma0**2)
[ ]Discrete chain versus closed formBrowser
chain_rng = np.random.default_rng(5)
K, t_end = 200, .3
x = np.tile([2.,0.],(20000,1))            # todas las cadenas parten de x0 = (2, 0)
step_alpha = np.exp(-beta*t_end/K)          # α_i = a(iΔ)/a((i-1)Δ), constante con β constante
for _ in range(K):
    x = np.sqrt(step_alpha)*x + np.sqrt(1-step_alpha)*chain_rng.standard_normal(x.shape)
a = alpha_bar(t_end)
print("media empírica:",x.mean(axis=0).round(4),"predicha:",(np.sqrt(a)*np.array([2.,0.])).round(4))
print("varianza empírica:",x.var(axis=0).round(4),"predicha:",round(float(1-a),4))

With 20000 chains, the standard error of the mean is 0.909/20000≈0.007\sqrt{0.909/20000}\approx0.007 per coordinate and that of the variance is 0.9092/20000≈0.0090.909\sqrt{2/20000}\approx0.009. The output differences range from nearly zero to 2.3 standard errors, largest for the mean at x2x_2. With four comparisons, these are consistent with sampling fluctuation. Every chain step is exact, so this cell checks the algebra of the telescoping product.

From noise to the score

The marginal score is st(x)=∇xlog⁡pt(x)s_t(\vb x)=\grad_{\vb x}\log p_t(\vb x). The network does not estimate it directly. It minimizes the simplified noise-prediction loss, E∥εθ(Xt,t)−ε∥2\E\norm{\varepsilon_\theta(X_t,t)-\varepsilon}^2, with random tt. Two results connect this objective to the score. The first gives the optimal prediction and minimum loss. The second converts that prediction into a score.

Proof

Write f−ε=(f−ε⋆)+(ε⋆−ε)f-\varepsilon=(f-\varepsilon^\star)+(\varepsilon^\star-\varepsilon) and expand the square. The cross term is 2 E[(f−ε⋆)⊤(ε⋆−ε)]2\,\E[(f-\varepsilon^\star)\T(\varepsilon^\star-\varepsilon)]. Conditioning on (Xt,t)(X_t,t) makes the first factor known, so it can be taken outside the conditional expectation, and E[ε⋆−ε∣Xt,t]=ε⋆−ε⋆=0\E[\varepsilon^\star-\varepsilon\given X_t,t]=\varepsilon^\star-\varepsilon^\star=\vb 0. The tower property makes the cross term zero. All expectations are finite because E∥ε∥2=2\E\norm{\varepsilon}^2=2 and E∥ε⋆∥2≤E∥ε∥2\E\norm{\varepsilon^\star}^2\le\E\norm{\varepsilon}^2 by Jensen’s inequality.

∎

The theorem turns an opaque number into an interpretable one. A loss of 0.27 alone is hard to assess because the minimum is not zero: given XtX_t, the noise is not determined. The oracle lets us calculate the minimum loss and interpret the difference as the network’s squared error. We will do this in the lab.

The second form is Tweedie’s formula: the score points from the noisy point toward the contracted posterior mean. We use the first form to convert the network output: sθ=−εθ/1−as_\theta=-\varepsilon_\theta/\sqrt{1-a}. With this conversion and ∇xlog⁡q(xt∣x0)=−ε/1−a\grad_{\vb x}\log q(\vb x_t\given\vb x_0)=-\varepsilon/\sqrt{1-a}, we have ∥εθ−ε∥2=(1−a) ∥sθ−∇log⁡q(xt∣x0)∥2\norm{\varepsilon_\theta-\varepsilon}^2=(1-a)\,\norm{s_\theta-\grad\log q(\vb x_t\given\vb x_0)}^2. The noise loss is denoising score matching weighted by 1−a1-a at each time, just as it is the DDPM variational bound with per-step weights removed. Reconstruct the central calculation before reading the full proof.

ProofFrom expected noise to the score
Prove: For independent Gaussian noise, derive the score of the marginal distribution of X_t from p_t(x) = ∫ q(x | x₀) p₀(dx₀), where q(x | x₀) is the density of N(√a x₀, (1−a) I).
0
Assume differentiation under the integral is valid; the proof justifies that step later.

Step 1 of 3. What is the gradient with respect to x of log q(x | x₀)?

Proof

Let φ(u)=(2π(1−a))−d/2exp⁡(−∥u∥2/(2(1−a)))\varphi(\vb u)=(2\pi(1-a))^{-d/2}\exp(-\norm{\vb u}^2/(2(1-a))). Independence gives pt(x)=E[φ(x−aX0)]p_t(\vb x)=\E[\varphi(\vb x-\sqrt a X_0)], which is positive because φ>0\varphi>0. The norm of the gradient ∇φ(u)=−u φ(u)/(1−a)\grad\varphi(\vb u)=-\vb u\,\varphi(\vb u)/(1-a) is bounded by a constant independent of u\vb u, because r↦re−r2/(2(1−a))r\mapsto r e^{-r^2/(2(1-a))} is bounded. Dominated convergence therefore allows differentiation under the expectation without any moment assumption on X0X_0:

∇pt(x)=−11−aE[(x−aX0) φ(x−aX0)].\grad p_t(\vb x)=-\frac{1}{1-a}\E\big[(\vb x-\sqrt aX_0)\,\varphi(\vb x-\sqrt aX_0)\big].

After division by pt(x)p_t(\vb x), Bayes’ rule shows that the weight φ(x−aX0)/pt(x)\varphi(\vb x-\sqrt aX_0)/p_t(\vb x) is the density of the posterior law of X0X_0 given Xt=xX_t=\vb x relative to the law of X0X_0. Hence st(x)=−(x−a E[X0∣Xt=x])/(1−a)s_t(\vb x)=-(\vb x-\sqrt a\,\E[X_0\given X_t=\vb x])/(1-a), giving the second form. Since Xt=aX0+1−a εX_t=\sqrt aX_0+\sqrt{1-a}\,\varepsilon, we also have E[ε∣Xt=x]=(x−a E[X0∣Xt=x])/1−a\E[\varepsilon\given X_t=\vb x]=(\vb x-\sqrt a\,\E[X_0\given X_t=\vb x])/\sqrt{1-a}, and substitution yields the first form.

∎

Combining both theorems, the optimal noise predictor is ε⋆=−1−a st\varepsilon^\star=-\sqrt{1-a}\,s_t. A network with noise-prediction error δ\delta yields score error δ/1−a\delta/\sqrt{1-a}. At t=0.01t=0.01, 1−a=0.277\sqrt{1-a}=0.277 and the error is multiplied by 3.61; at tmin⁡t_{\min} it is multiplied by 7.94. Dividing by variance 1−a1-a instead of standard deviation erroneously multiplies the score by an additional 1/1−a1/\sqrt{1-a}: 3.61 at t=0.01t=0.01.

NumericThe cost of confusing variance and standard deviation
At t=0.01t=0.01, with a(t)=e−8ta(t)=e^{-8t}, someone converts the noise prediction to a score using −εθ/(1−a)-\varepsilon_\theta/(1-a) instead of −εθ/1−a-\varepsilon_\theta/\sqrt{1-a}. By what factor is the resulting score multiplied relative to the correct one?

The mixture oracle

Because it does not depend on another network, this check catches sign, scale, and training errors. Two choices remain: the distribution used to select evaluation points and the norm used to aggregate error. Both affect the conclusion, as the figure shows.

Proof

Let ZZ be the component label, with P(Z=k)=πkP(Z=k)=\pi_k. Given Z=kZ=k, X0=μk+Σk1/2ηX_0=\vb\mu_k+\mat\Sigma_k^{1/2}\vb\eta with standard normal η\vb\eta independent of ε\varepsilon. Therefore Xt=a μk+a Σk1/2η+1−a εX_t=\sqrt a\,\vb\mu_k+\sqrt a\,\mat\Sigma_k^{1/2}\vb\eta+\sqrt{1-a}\,\varepsilon is an affine transformation of a normal vector, hence normal with mean a μk\sqrt a\,\vb\mu_k and covariance aΣk+(1−a)Ia\mat\Sigma_k+(1-a)\mat I. The covariance is positive definite because 1−a>01-a>0, even if Σk\mat\Sigma_k is singular. By total probability ptp_t is the stated mixture, the convolution of each component with the Gaussian noise. For each component, ∇xN(x;m,C)=−C−1(x−m) N(x;m,C)\grad_{\vb x}\Normal(\vb x;\vb m,\mat C)=-\mat C^{-1}(\vb x-\vb m)\,\Normal(\vb x;\vb m,\mat C). Weighting by πk\pi_k and dividing by pt(x)>0p_t(\vb x)>0 gives the formula because πkNk/pt=rk\pi_k\Normal_k/p_t=r_k.

∎

The responsibilities rkr_k are the Gaussian mixture posterior probabilities evaluated at the noisy distribution. Far from the modes, the numerators are exponentials of very negative numbers and underflow in floating point. We therefore use log-sum-exp, subtracting the largest exponent before exponentiating. Here every covariance is 0.09I0.09\mat I, each Ck\mat C_k is the same multiple of the identity, and normalization factors cancel in rkr_k. The “Mixture and exact score” cell uses this simplification. The final exercise asks for the general case.

At an exactly symmetric point such as the origin, the exact score is zero. Dividing each point’s error by its score norm and averaging can therefore explode even with small absolute error. We use the ratio of the RMS error to the RMS exact score on points drawn from ptp_t. This metric weights by density. The tails require a separate region-by-region examination.

A network and its derivative from scratch

The network receives (x1,x2,t,sin⁡πt,cos⁡πt)(x_1,x_2,t,\sin\pi t,\cos\pi t), applies a hidden layer of 48 tanh units and produces two noise components. Periodic functions of time give the network an inexpensive way to represent nonlinear dependence on tt. We sample times with t=tmin⁡+(1−tmin⁡)U2t=t_{\min}+(1-t_{\min})U^2 and uniform UU, so the probability of t<0.1t<0.1 is (0.1−tmin⁡)/(1−tmin⁡)≈0.31\sqrt{(0.1-t_{\min})/(1-t_{\min})}\approx0.31 instead of 0.1. Low noise receives more examples because converting to a score amplifies errors most strongly there. This weighting changes which errors matter most during training, but not the minimizer at each tt, which remains ε⋆\varepsilon^\star.

The manual derivative can be checked. If H=tanh⁡(FW1+b1)\mat H=\tanh(\mat F\mat W_1+\vb b_1) and ε^=HW2+b2\hat\varepsilon=\mat H\mat W_2+\vb b_2, for the mean loss equal to half the squared norm over a batch of size BB, the output gradient is E=(ε^−ε)/B\mat E=(\hat\varepsilon-\varepsilon)/B. Then ∂L/∂W2=H⊤E\partial L/\partial\mat W_2=\mat H\T\mat E, the gradient with respect to hidden preactivation FW1+b1\mat F\mat W_1+\vb b_1 is (EW2⊤)⊙(1−H⊙H)(\mat E\mat W_2\T)\odot(1-\mat H\odot\mat H) because tanh⁡′=1−tanh⁡2\tanh'=1-\tanh^2, giving W1\mat W_1 and b1\vb b_1. Before training, we check one gradient entry with finite differences. A falling loss does not prove the backward pass is correct, since a gradient with a scale error or an error in just one layer can also reduce it.

[ ]MLP and gradient checkBrowser
import json
train_rng = np.random.default_rng(2027)
hidden = 48
params = [train_rng.normal(0,1/np.sqrt(5),(5,hidden)), np.zeros(hidden),
          train_rng.normal(0,.05,(hidden,2)), np.zeros(2)]
first = [np.zeros_like(p) for p in params]
second = [np.zeros_like(p) for p in params]
iteration = 0

def features(x,t):
    t = np.broadcast_to(t,(len(x),))
    return np.column_stack((x,t,np.sin(np.pi*t),np.cos(np.pi*t)))

def loss_grad(parameters, x, t, noise):
    w1,b1,w2,b2 = parameters
    f = features(x,t)
    h = np.tanh(f@w1+b1)
    diff = h@w2+b2-noise
    loss = .5*np.mean(np.sum(diff**2,axis=1))
    e = diff/len(x)
    dh = (e@w2.T)*(1-h*h)
    return loss,[f.T@dh,dh.sum(axis=0),h.T@e,e.sum(axis=0)]

probe_rng = np.random.default_rng(99)
px = probe_rng.normal(size=(7,2))
pt = probe_rng.uniform(.01,1,size=7)
pz = probe_rng.normal(size=(7,2))
_, gradients = loss_grad(params,px,pt,pz)
h = 1e-5
plus = [p.copy() for p in params]; plus[0][0,0] += h
minus = [p.copy() for p in params]; minus[0][0,0] -= h
finite = (loss_grad(plus,px,pt,pz)[0]-loss_grad(minus,px,pt,pz)[0])/(2*h)
assert np.isclose(finite,gradients[0][0,0],rtol=1e-5,atol=1e-8)
print("gradiente analítico:",gradients[0][0,0],"diferencia finita:",finite)

def train_steps(count):
    global iteration
    losses = []
    for _ in range(count):
        iteration += 1
        x0 = sample_data(128,train_rng)
        t = t_min+(1-t_min)*train_rng.random(128)**2
        a = alpha_bar(t)
        noise = train_rng.standard_normal((128,2))
        x = np.sqrt(a)[:,None]*x0 + np.sqrt(1-a)[:,None]*noise
        loss, grads = loss_grad(params,x,t,noise)
        for i,g in enumerate(grads):
            first[i][:] = .9*first[i]+.1*g
            second[i][:] = .999*second[i]+.001*g*g
            mhat = first[i]/(1-.9**iteration)
            vhat = second[i]/(1-.999**iteration)
            params[i] -= .002*mhat/(np.sqrt(vhat)+1e-8)
        losses.append(loss)
    print("pasos:",iteration,"pérdida media del bloque:",np.mean(losses))

Full training consists of 15000 Adam steps in batches of 128, divided into six blocks of 2500 so each cell finishes within seconds in the browser. The six cells continue the same session. Rerunning one block adds steps and no longer reproduces the interactive’s weights. To repeat the run, rerun the “MLP and gradient check” cell, which resets parameters, optimizer and random generator, followed by all six blocks in order.

[ ]Training, first blockBrowser
train_steps(2500)
[ ]Training, second blockBrowser
train_steps(2500)
[ ]Training, third blockBrowser
train_steps(2500)
[ ]Training, fourth blockBrowser
train_steps(2500)
[ ]Training, fifth blockBrowser
train_steps(2500)
[ ]Training, sixth blockBrowser
train_steps(2500)

Mean loss per block quickly drops to 0.275, then changes little through 0.271. That mean includes the steps within each block; the final network, measured below on 50000 new examples, scores 0.266. Without an oracle we could not know how much improvement remains. With one, we can.

Measure the network against the oracle

The interactives use final parameters rounded to four decimal places. We apply the same rounding before measuring and sampling so that the lesson and figures refer to the same network.

[ ]Publish the network and measure its scoreBrowser
rounded = [np.round(p,4) for p in params]
def learned_score(x,t):
    a = alpha_bar(t)
    if not 0 < t <= 1:
        raise ValueError("El score aprendido requiere tiempo positivo")
    w1,b1,w2,b2 = rounded
    return -(np.tanh(features(x,t)@w1+b1)@w2+b2)/np.sqrt(1-a)

test_rng = np.random.default_rng(123)
for t in (.01,.05,.2,.5,1.):
    x = noisy_sample(1024,t,test_rng)
    truth, predicted = exact_score(x,t), learned_score(x,t)
    relative = np.sqrt(np.mean((predicted-truth)**2))/max(np.sqrt(np.mean(truth**2)),1e-12)
    print("t",t,"error RMS relativo:",round(float(relative),5))
for name,p in zip(("W1","b1","W2","b2"),rounded):
    print("huella de",name,p.shape,"suma de valores absolutos:",round(float(np.abs(p).sum()),4))

The final fingerprint checks that your run exactly reproduces the network used in the interactives. Relative RMS error is 0.179 at t=0.01t=0.01, 0.112 at t=0.05t=0.05 and 0.045 at t=0.5t=0.5. The network performs much worse at low noise. Two effects combine: the factor 1/1−a1/\sqrt{1-a} amplifies any noise-prediction error, and at low noise the score varies rapidly across space, making it harder for a 48-unit network to follow. We now use the first theorem to translate loss into network error.

[ ]Minimum loss with the oracleBrowser
def oracle_noise(x,t):
    # ε* = E[ε | X_t = x] = -sqrt(1-a) s_t(x), con un tiempo distinto por fila
    a = alpha_bar(t)[:,None]
    variance = 1-a+a*sigma0**2
    delta = x[:,None,:]-np.sqrt(a)[:,:,None]*means[None]
    logits = -(delta**2).sum(axis=-1)/(2*variance)
    r = np.exp(logits-logits.max(axis=1,keepdims=True))
    r /= r.sum(axis=1,keepdims=True)
    return np.sqrt(1-a)*(r[:,:,None]*delta).sum(axis=1)/variance

eval_rng = np.random.default_rng(321)
n = 50000
tt = t_min+(1-t_min)*eval_rng.random(n)**2
aa = alpha_bar(tt)[:,None]
z = eval_rng.standard_normal((n,2))
xt = np.sqrt(aa)*sample_data(n,eval_rng)+np.sqrt(1-aa)*z
w1,b1,w2,b2 = rounded
net = np.tanh(features(xt,tt)@w1+b1)@w2+b2
star = oracle_noise(xt,tt)
print("pérdida de la red:",round(float(.5*np.mean(np.sum((net-z)**2,axis=1))),5))
print("pérdida mínima, la del oráculo:",round(float(.5*np.mean(np.sum((star-z)**2,axis=1))),5))
print("exceso medido directamente:",round(float(.5*np.mean(np.sum((net-star)**2,axis=1))),5))

Minimum loss is approximately 0.260 and network loss is 0.266, placing the network roughly six thousandths above the optimum. Directly measured excess (0.0060) agrees with the difference (0.0056) up to sampling fluctuations, because the theorem’s cross term is zero only in expectation. This 2% excess in loss is small on average, but the average is dominated by times and regions with many samples. The next question is where it is concentrated.

[ ]Where the network failsBrowser
where_rng = np.random.default_rng(11)
for t in (.01,.05,.2,1.):
    a = alpha_bar(t); sd = np.sqrt(1-a+a*sigma0**2)
    x = noisy_sample(50000,t,where_rng)
    distance = np.min(np.linalg.norm(x[:,None,:]-np.sqrt(a)*means,axis=-1),axis=1)
    truth = exact_score(x,t)
    error = learned_score(x,t)-truth
    def relative(mask):
        return np.sqrt(np.mean(error[mask]**2)/np.mean(truth[mask]**2))
    near, far = distance < 2*sd, distance > 3*sd
    gap = far & (np.linalg.norm(x,axis=1) < 2*np.sqrt(a))   # lejos y dentro del anillo de centros
    detail = (f" (en el hueco, {gap.sum()/far.sum():.0%} de los lejanos: {relative(gap):.3f}; "
              f"en las colas exteriores: {relative(far & ~gap):.3f})") if gap.any() else ""
    print(f"t={t}: masa lejos {far.mean():.4f}; error relativo cerca {relative(near):.3f}, "
          f"lejos {relative(far):.3f}{detail}; error medio {error.mean(axis=0).round(3)}")

“Near” means points within two standard deviations of the mean of their nearest mode; “far” means points beyond three. At t=0.01t=0.01 only 1.1% of the mass is far, where relative error is more than triple that near the modes (0.394 versus 0.103). The far region forms a ring around each mode, which the cell divides in two: 45% of those points fall in the gap inside the ring formed by the four centers, where relative error reaches 0.59 versus 0.23 in the outer tails. Starting at t=0.05t=0.05, three standard deviations already exceed each center’s distance to the gap, so “far” means outer tails only. At t=0.2t=0.2 the difference almost disappears (0.088 versus 0.083). At t=1t=1 it reappears (0.091 versus 0.056) for a different reason: the four modes have merged near the origin and “far” now denotes the cloud’s outer tails, where the network must extrapolate. We will revisit this during sampling. The explanation for the gap between modes is statistical: loss averages over the noisy data distribution, and at low noise almost no training examples fall between modes. Data weakly constrain the field there, so the network interpolates as it can. This is an expected pattern, not a guarantee that every network fails in the same way.

The last column is subtler. Mean error is not zero: it has a systematic negative component in x1x_1: −0.15-0.15 at t=0.01t=0.01, −0.07-0.07 at t=0.05t=0.05 and −0.05-0.05 at t=0.2t=0.2. A constant score bias pushes every particle in the same direction, and in the region where modes separate this is enough to change how many end up in each mode. We will check this while sampling.

Return from noise to data

The reverse-time process depends on the score. For an SDE  ⁣dX=f(X,t)  ⁣dt+g(t)  ⁣dW\dd X=f(X,t)\,\dd t+g(t)\,\dd W, Anderson’s (1982) result, used by Song and collaborators, says that the process traversed backward in time solves  ⁣dX=[f−g2st(X)]  ⁣dt+g  ⁣dWˉ\dd X=[f-g^2 s_t(X)]\,\dd t+g\,\dd\bar W with  ⁣dt<0\dd t<0. For our VP process, f(x,t)=−4xf(\vb x,t)=-4\vb x and g2=8g^2=8. With a positive increment Δ\Delta advancing toward smaller times, Euler–Maruyama applies

xt−Δ=xt+(4xt+8st(xt))Δ+8Δ z,z∼N(0,I).\vb{x}_{t-\Delta}=\vb{x}_t+\big(4\vb{x}_t+8s_t(\vb{x}_t)\big)\Delta+\sqrt{8\Delta}\,\vb z,\qquad \vb z\sim\Normal(\vb 0,\mat I).

The probability-flow ODE  ⁣dX=[f−12g2st(X)]  ⁣dt\dd X=[f-\tfrac12g^2s_t(X)]\,\dd t removes noise, and its Euler step is xt−Δ=xt+4(xt+st(xt))Δ\vb{x}_{t-\Delta}=\vb{x}_t+4(\vb{x}_t+s_t(\vb{x}_t))\Delta. The factor 12\tfrac12 before g2g^2 compensates for the removed diffusion. In the continuous limit and with the exact score, SDE and ODE have the same marginals ptp_t. They do not produce the same trajectories, and their finite discretizations have different errors.

The third sampler is the DDPM ancestral step. For a=a(t)a=a(t), a′=a(t−Δ)a'=a(t-\Delta), α=a/a′\alpha=a/a' and βd=1−α\beta_d=1-\alpha, the exact posterior q(xt−Δ∣xt,x0)q(\vb x_{t-\Delta}\given\vb x_t,\vb x_0) is Gaussian. Replacing x0\vb x_0 by Tweedie’s estimate reduces its mean to (x+βdst(x))/α(\vb{x}+\beta_d s_t(\vb{x}))/\sqrt\alpha, equation 11 of Ho and collaborators written with εθ=−1−a sθ\varepsilon_\theta=-\sqrt{1-a}\,s_\theta. We use variance β~=βd(1−a′)/(1−a)\tilde\beta=\beta_d(1-a')/(1-a). This is a Gaussian approximation of the reverse transition rather than the exact reverse transition of a mixture with finite steps.

For scale, Ho and collaborators used 1000 steps with variances βi\beta_i increasing linearly from 10−410^{-4} to 0.020.02. On unconditional CIFAR-10, their simplified objective achieved FID 3.17 against the training set and 5.24 against the test set. These image results use a different protocol and do not predict what we measure here.

The initial condition matters too. Because a(1)>0a(1)>0, p1p_1 is not exactly N(0,I)\Normal(\vb 0,\mat I). Here each sampler starts from exact p1p_1 by first generating X0X_0 and noise. This is possible only because the toy distribution is known. A practical model starts from the standard normal and accepts the corresponding error, negligible with a(1)=3.4×10−4a(1)=3.4\times10^{-4}. You can check this in the interactive.

InteractiveParticles returning to the modes
−44x₁x₂
  • 2000 particles (fixed seed)
  • Components of p_t: two-standard-deviation circle
Sampler
Score
Start
20
100
Current time0.002
Steps completed20
MMD² against p_t0.0120
Share by mode (%)26 · 25 · 25 · 25
Outside the displayed plane0
Two thousand reproducible particles start from p1p_1 (or the standard normal) and integrate toward tmin⁡=0.002t_{\min}=0.002. The progress control can pause the reverse process. MMD² compares one thousand of those particles with one thousand points from the exact marginal ptp_t at the displayed time. The mode split reports the percentage of particles nearest to each mode in the order +x1+x_1, −x1-x_1, +x2+x_2, −x2-x_2. Dashed circles mark two standard deviations of each component of ptp_t.

Start with the ODE, exact score and 20 steps. The modes look inflated and MMD² is around 0.012: the final Euler steps jump across the region where the score changes fastest. Increase to 100 and 200 steps with the same exact score and watch the clouds narrow and MMD² drop below 0.001. This error comes from the integrator. Next select “Learned” with 200 ODE steps. The clouds retain their shape, but the mode split becomes imbalanced (the −x1-x_1 mode receives about 30% of the particles and +x1+x_1 about 19%), MMD² rises to around five thousandths and “Outside displayed plane” rises from 0 to 8: some particles leave the cloud. The first effect makes the previous cell’s bias visible; we will explain the second through measurement. Finally, return to the exact score and switch the start to N(0,I)\Normal(\vb 0,\mat I). MMD² and the mode split shift only within sampling fluctuations because the difference from exact p1p_1 is too small for the figure to resolve.

The widget uses the same mixture and rounded weights as the cells, but its pseudorandom generator differs from NumPy’s, so coordinates and exact values differ within sampling fluctuations.

[ ]Reverse samplersBrowser
def reverse_sample(method, score, steps, n, seed):
    if method not in ("sde","ode","ddpm") or steps < 1:
        raise ValueError("Método o número de pasos inválido")
    rng = np.random.default_rng(seed)
    x = noisy_sample(n,1.,rng)
    dt = (1-t_min)/steps
    for i in range(steps):
        t = 1-i*dt
        s = score(x,t)
        if method == "ode":
            x = x+4*(x+s)*dt
        elif method == "sde":
            x = x+(4*x+8*s)*dt+np.sqrt(8*dt)*rng.standard_normal(x.shape)
        else:
            a, previous = alpha_bar(t), alpha_bar(t-dt)
            alpha = a/previous
            b = 1-alpha
            variance = b*(1-previous)/(1-a)
            x = (x+b*s)/np.sqrt(alpha)+np.sqrt(variance)*rng.standard_normal(x.shape)
    return x

def mode_report(x, t):
    """Fracción de puntos por modo y desviación por coordenada respecto del modo más cercano."""
    centers = np.sqrt(alpha_bar(t))*means
    nearest = np.argmin(((x[:,None,:]-centers)**2).sum(axis=-1),axis=1)
    residual = x-centers[nearest]
    return np.bincount(nearest,minlength=4)/len(x), float(np.sqrt(np.mean(residual**2)))

target = float(np.sqrt(1-alpha_bar(t_min)+alpha_bar(t_min)*sigma0**2))
print("desviación por coordenada de cada modo en p(t_min):",round(target,4))
for method in ("sde","ode","ddpm"):
    spreads = [round(mode_report(reverse_sample(method,exact_score,steps,2000,7),t_min)[1],3)
               for steps in (20,100,500)]
    print(method,"con score exacto; desviación con 20, 100 y 500 pasos:",spreads)

With the exact score, each mode’s standard deviation approaches 0.323 as the step count increases, but slowly. At 100 uniform steps the SDE yields 0.397 and the ODE 0.371; at 500 they still yield 0.336 and 0.331. The grid is uniform in tt while difficulty is not. Near tmin⁡t_{\min}, each component’s score is −(x−aμk)/v-(\vb x-\sqrt a\vb\mu_k)/v with v≈0.10v\approx0.10, and with Δ≈0.01\Delta\approx0.01 the SDE term 8sΔ8s\Delta cuts approximately 76% of the distance to the mode center in a single step. With contractions that large, Euler’s linearization is no longer reliable.

The DDPM step errs in the opposite direction. Its mean equals that of the true reverse transition: posterior q(xt−Δ∣xt,x0)q(\vb x_{t-\Delta}\given\vb x_t,\vb x_0) has a mean linear in x0\vb x_0 and fixed covariance, so averaging over the law of X0X_0 given XtX_t amounts to replacing x0\vb x_0 by E[X0∣Xt]\E[X_0\given X_t], which is exact with the exact score. Its covariance β~I\tilde\beta\mat I, however, omits uncertainty in X0X_0 given XtX_t, which would add a term of order Δ2\Delta^2 per step. The omitted term drives dispersion below its proper value. At 20 steps, the approximation’s other defect dominates: with long steps the true transition is far from Gaussian, yielding 0.41, above the target but much better than SDE and ODE. At 100, the omission dominates and it falls to 0.271, below target; at 500 it still gives 0.304. None of the three reaches the target with 100 uniform steps. These figures are the integrator error floor. Comparisons with the network must use the same method and step count, and cannot expect to improve that floor.

Measure samples with MMD

The maximum mean discrepancy (MMD) compares distributions using a kernel. We use the unbiased MMD⁡2\operatorname{MMD}^2 estimator of Gretton and colleagues, with RBF kernel k(x,y)=exp⁡(−∥x−y∥2/2)k(\vb x,\vb y)=\exp(-\norm{\vb x-\vb y}^2/2) of width one in the example’s units. The estimator may be negative even though population MMD squared is nonnegative. We do not clip it to zero, because clipping would introduce bias.

The reference uses the same metric between two independent samples from the true distribution p0p_0. Its spread establishes the scale of sampling fluctuation. Sample size determines power. With 256 points per side, reference fluctuation is of order 10−210^{-2} and hides all errors measured so far. With 1024 it falls to order 10−310^{-3}, while the quadratic cost of three 1024×10241024\times1024 matrices per comparison remains manageable in the browser. Generated samples stop at tmin⁡t_{\min} and are compared with p0p_0. Population MMD² between ptmin⁡p_{t_{\min}} and p0p_0 is 1.3×10−41.3\times10^{-4}. It has a closed form. If X∼N(m1,s12I)X\sim\Normal(\vb m_1,s_1^2\mat I) and Y∼N(m2,s22I)Y\sim\Normal(\vb m_2,s_2^2\mat I) are independent in the plane, X−YX-Y is normal with covariance (s12+s22)I(s_1^2+s_2^2)\mat I, and a Gaussian integral gives E k(X,Y)=c−1exp⁡(−∥m1−m2∥2/(2c))\E\,k(X,Y)=c^{-1}\exp(-\norm{\vb m_1-\vb m_2}^2/(2c)) with c=1+s12+s22c=1+s_1^2+s_2^2. MMD² between two mixtures is a double sum of those terms, evaluated by the cell. This is the minimum bias due to stopping at tmin⁡t_{\min}.

[ ]MMD² and reference between true samplesBrowser
def mmd2_unbiased(x,y):
    if len(x)<2 or len(y)<2:
        raise ValueError("Se necesitan al menos dos puntos en cada muestra")
    def kernel(a,b):
        d2 = np.maximum(0,(a*a).sum(1)[:,None]+(b*b).sum(1)[None,:]-2*a@b.T)
        return np.exp(-d2/2)
    xx, yy, xy = kernel(x,x),kernel(y,y),kernel(x,y)
    n,m = len(x),len(y)
    return ((xx.sum()-np.trace(xx))/(n*(n-1))+
            (yy.sum()-np.trace(yy))/(m*(m-1))-2*xy.mean())

sizes = (256,1024)
for N in sizes:
    baseline = []
    for seed in range(8):
        x = sample_data(N,np.random.default_rng(1000+2*seed))
        y = sample_data(N,np.random.default_rng(1001+2*seed))
        baseline.append(float(mmd2_unbiased(x,y)))
    print(f"N={N}: referencia MMD² en ocho pares independientes:",np.round(baseline,6))
    print(f"N={N}: rango observado:",round(min(baseline),6),round(max(baseline),6))

def expected_kernel(m1,s1,m2,s2):
    """E k(X,Y) promediado sobre las componentes de dos mezclas equiponderadas e isotrópicas."""
    c = 1+s1**2+s2**2
    d2 = ((m1[:,None,:]-m2[None,:,:])**2).sum(axis=-1)
    return float(np.mean(np.exp(-d2/(2*c))/c))
a_min = float(alpha_bar(t_min))
m_min, s_min = np.sqrt(a_min)*means, np.sqrt(1-a_min+a_min*sigma0**2)
population = (expected_kernel(means,sigma0,means,sigma0)+expected_kernel(m_min,s_min,m_min,s_min)
              -2*expected_kernel(means,sigma0,m_min,s_min))
print("MMD² poblacional entre p(t_min) y p_0:",f"{population:.2e}")

Each comparison below uses five seed pairs and 100 steps at both sample sizes. The generated and true samples use random generators separate from those used for the reference.

[ ]Compare oracle and network: SDEBrowser
def compare(method):
    for N in sizes:
        for label, score in (("exacto",exact_score),("aprendido",learned_score)):
            values = []
            for seed in range(5):
                reference = sample_data(N,np.random.default_rng(1900+2*seed))
                generated = reverse_sample(method,score,100,N,1901+2*seed)
                values.append(float(mmd2_unbiased(generated,reference)))
            print(f"N={N}",method,label,"MMD² por pareja:",np.round(values,6),
                  "media:",round(float(np.mean(values)),6))
compare("sde")
[ ]Compare oracle and network: ODEBrowser
compare("ode")
[ ]Compare oracle and network: DDPMBrowser
compare("ddpm")

With 256 points per side, all six averages, oracle and network for each sampler, lie within the reference range from −0.0049-0.0049 to 0.01140.0114. At this size the test distinguishes none of them. With 1024 points, the reference range narrows to [−0.0012, 0.0014][-0.0012,\ 0.0014] and the picture changes. For the oracle, ODE (mean 0.00054) and DDPM (0.00036) stay inside it, but SDE yields 0.00165 above it. This is the integrator floor already seen in mode deviations, now detected by the metric. For the network, all three averages fall outside: 0.0049 for SDE, 0.0058 for ODE, and 0.0026 for DDPM. Every one of the fifteen pairs exceeds the reference maximum. This is the requested measurable outcome: oracle-sample MMD is comparable to that of two true samples, while network-sample MMD is not.

MMD detects a difference without explaining it. The oracle enables a targeted test: if the network assigns mass unevenly across modes, mode counts from many samples will show it. Under equal weights, counts from nn samples follow a multinomial distribution and statistic χ2=∑k(nk−n/4)2/(n/4)\chi^2=\sum_k(n_k-n/4)^2/(n/4) is approximately chi-squared with 3 degrees of freedom, whose 5% threshold is 7.81.

[ ]Mode allocationBrowser
for method in ("sde","ode","ddpm"):
    for label, score in (("exacto",exact_score),("aprendido",learned_score)):
        share, spread = mode_report(reverse_sample(method,score,100,4000,77),t_min)
        chi2 = float(np.sum((share*4000-1000)**2/1000))
        print(method,label,"reparto (+x1, -x1, +x2, -x2):",np.round(share,3),
              "chi² =",round(chi2,1),"desviación:",round(spread,3))
print("umbral de la ji cuadrado con 3 grados de libertad al 5 %: 7.81")

With the network, all three samplers clearly reject equal weights: χ2=43.1\chi^2=43.1 for SDE, 166.4 for ODE, and 48.5 for DDPM. All show the same pattern: the mode at +x1+x_1 receives 17–22% of particles and the mode at −x1-x_1 29–32%, while the two x2x_2-axis modes stay near 25%. This matches the negative mean error in x1x_1 from the “Where the network fails” cell. The deterministic ODE is most affected because no noise perturbs its trajectory. With the oracle, SDE and DDPM fall below threshold and ODE barely exceeds it (8.0). With the exact score, no sampler can favor a mode: the mixture, initialization, and all three update rules are symmetric under 90∘90^\circ rotations. Their sample law is therefore symmetric too, and each mode receives exactly one quarter in expectation, even when the integrator distorts the clouds. The next cell repeats the test on nine other seeds to see whether the result is a seed fluctuation.

[ ]Oracle χ² with other seedsBrowser
values = []
for seed in range(78,87):
    share, _ = mode_report(reverse_sample("ode",exact_score,100,4000,seed),t_min)
    values.append(round(float(np.sum((share*4000-1000)**2/1000)),1))
print("EDO con score exacto, nueve semillas más:",values,"media:",round(float(np.mean(values)),2))

All nine values fall below threshold, and their mean 2.2 is compatible with 3, the expectation of a chi-squared distribution with 3 degrees of freedom. The 8.0 was one seed’s fluctuation, exactly the kind of event a 5% test produces about once in twenty trials.

The last column of the mode-allocation cell hides another surprise. With the network and ODE, deviation from the nearest mode is 0.799, twice the oracle value. The visible clouds do not explain it. A few particles ending far from every mode do.

[ ]Escaping particlesBrowser
centers_min = np.sqrt(alpha_bar(t_min))*means
start_radius = np.linalg.norm(noisy_sample(4000,1.,np.random.default_rng(77)),axis=1)  # el mismo inicio que la celda del reparto
for method in ("sde","ode","ddpm"):
    final = reverse_sample(method,learned_score,100,4000,77)
    distance = np.min(np.linalg.norm(final[:,None,:]-centers_min,axis=-1),axis=1)
    escaped = distance > 1.5
    print(f"{method}: escapan {escaped.mean():.2%}; distancia máxima {distance.max():.1f}; "
          f"escapan {escaped[start_radius>3].mean():.0%} de las que empiezan a radio > 3; "
          f"desviación sin ellas {np.sqrt(np.mean(distance[~escaped]**2)/2):.3f}")
for r in (2.,4.,8.):
    x = np.array([[r,r]])/np.sqrt(2)
    ratio = float(learned_score(x,1.)[0]@x[0]/(exact_score(x,1.)[0]@x[0]))
    print(f"t=1, radio {r:.0f}: componente radial del score de la red / la del exacto = {ratio:.2f}")

With the ODE, 1.3% of particles end more than 1.5 units from every mode, some tens of units away. Without them the deviation is 0.387, close to the oracle’s 0.378. Almost all come from the p1p_1 tail: roughly 80% of those starting beyond radius 3 escape. The reason is the network’s tail score. At t=1t=1, p1p_1 is nearly N(0,I)\Normal(\vb 0,\mat I) and the exact score nearly −x-\vb x. The network saw few examples with ∥x∥>3\norm{\vb x}>3, around 1% of p1p_1, and extrapolates a shorter score: at radius 8 its radial component is half the exact one. The ODE drift 4(x+s)4(\vb x+s) leaves a particle stationary only when s=−xs=-\vb x exactly. With s=−c xs=-c\,\vb x and c<1c<1 it pushes the particle outward at rate 4(1−c)4(1-c), with nothing to bring it back. For SDE, and for DDPM to first order in Δ\Delta, the drift is 4x+8s4\vb x+8s, which still attracts while c>1/2c>1/2. Thus no particle ends more than 1.8 units from a mode under those methods, and none starting beyond radius 3 escapes. The 0.53% of SDE particles past 1.5 belong to tails of slightly wider clouds. A deterministic sampler inherits the network’s extrapolation errors in the prior tails without damping.

Practice with another mixture

The earlier oracle uses equal spherical covariances. In a general mixture, each component must solve its own linear system with Ck\mat C_k and add log⁡πk−12log⁡det⁡Ck\log\pi_k-\tfrac12\log\det\mat C_k to its exponent because weights and normalization factors no longer cancel in responsibilities. Normalize responsibilities per point by summing over components, rather than per component over the sample.

CodeScore of a noisy Gaussian mixture
Implement gmm_noisy_score(x, means, covs, weights, alpha_bar), using responsibilities normalized per point and linear systems per component. Assume positive weights summing to one, positive-definite covariances, and alpha_bar between zero and one. Return an array with the same shape as x.
import numpy as np

def gmm_noisy_score(x, means, covs, weights, alpha_bar):
  # x: (n,2), means: (k,2), covs: (k,2,2)
  # weights positivas que suman uno; covarianzas definidas positivas.
  # Devuelve un array (n,2).
  pass
Shift+Enter to run
QuizWhy it fails between modes
At t=0.01t=0.01, the relative error of the learned score in the gap between modes (0.59) is more than five times its error near them (0.103). What is the main explanation?
QuizWhat an MMD within the range tells us
The mean MMD² between network samples and the ground truth lies within the reference range between true samples, with 256 points per side. What can you conclude?
Key idea

A diffusion process is approximately reversed by following its score. We obtain the score from a noise predictor by dividing by the noise standard deviation 1−a\sqrt{1-a}. For a Gaussian mixture, the exact score is known at every time, letting us measure the minimum achievable loss, network error by time and region, integrator error floor, and sample bias separately. Aggregate metrics such as mean loss or a low-power MMD can hide failures that become visible through these targeted checks.