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 , a low noise level. The density-weighted relative error is 0.207, while uniform measurement over the square gives 0.290. The discrepancy is concentrated between modes, near the origin and in the corners, where little probability mass lies. The marked point is on the side of the mode facing the gap. The exact score pushes strongly toward that mode. The network points in nearly the same direction but at less than half the length, , giving a local discrepancy of 0.83 times the score RMS. Now click on the diagonal. A saddle point of lies very nearby: both scores are short and differ in direction by about , but the absolute discrepancy is small (0.12). Between modes, the main error is the magnitude on slopes descending toward the gap. Then raise to . Both errors fall to 0.07 and become equal because noise has filled the gap between modes.
The toy process
This is an Ornstein–Uhlenbeck process, so its law conditioned on is available without numerical integration. Its mean satisfies , hence . The variance per coordinate satisfies with , hence . Writing ,
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, , so is very close to but does not equal it. Second, the network is trained only for because converting predicted noise to a score divides by , which vanishes at . The samplers stop at , where each mode has standard deviation per coordinate instead of .
Signal, noise and mode separation
The process’s conventional signal-to-noise ratio (SNR) is
It compares the squared signal multiplier with the added noise variance. It equals 1 at and decreases monotonically. It is the variance ratio only when the data have unit variance per coordinate. Here , so the actual variance ratio is .
For a mixture, a different quantity determines the behavior: the distance between neighboring component means measured in component standard deviations. The means of and are apart, and each component has standard deviation . The ratio is 3.71 at , 2.47 at , 1.41 at , and 0.89 at . Between and 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.
From the SDE to discrete steps
The DDPM of Ho and colleagues works in discrete time: each step multiplies by and adds independent Gaussian noise of variance , yielding a forward process whose marginal has a closed form with . If we divide into steps of length and take , the telescoping product gives exactly. The discrete chain therefore has the same marginals as the SDE at the grid points. Also , so discrete is the continuous rate times the step length.
Step 1 of 3. Why is X_i given x₀ still Gaussian?
The first cell defines the mixture, sampling from , 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.
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)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 per coordinate and that of the variance is . The output differences range from nearly zero to 2.3 standard errors, largest for the mean at . 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 . The network does not estimate it directly. It minimizes the simplified noise-prediction loss, , with random . 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 and expand the square. The cross term is . Conditioning on makes the first factor known, so it can be taken outside the conditional expectation, and . The tower property makes the cross term zero. All expectations are finite because and 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 , 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: . With this conversion and , we have . The noise loss is denoising score matching weighted by 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.
Step 1 of 3. What is the gradient with respect to x of log q(x | x₀)?
Proof
Let . Independence gives , which is positive because . The norm of the gradient is bounded by a constant independent of , because is bounded. Dominated convergence therefore allows differentiation under the expectation without any moment assumption on :
After division by , Bayes’ rule shows that the weight is the density of the posterior law of given relative to the law of . Hence , giving the second form. Since , we also have , and substitution yields the first form.
∎Combining both theorems, the optimal noise predictor is . A network with noise-prediction error yields score error . At , and the error is multiplied by 3.61; at it is multiplied by 7.94. Dividing by variance instead of standard deviation erroneously multiplies the score by an additional : 3.61 at .
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 be the component label, with . Given , with standard normal independent of . Therefore is an affine transformation of a normal vector, hence normal with mean and covariance . The covariance is positive definite because , even if is singular. By total probability is the stated mixture, the convolution of each component with the Gaussian noise. For each component, . Weighting by and dividing by gives the formula because .
∎The responsibilities 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 , each is the same multiple of the identity, and normalization factors cancel in . 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 . This metric weights by density. The tails require a separate region-by-region examination.
A network and its derivative from scratch
The network receives , 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 . We sample times with and uniform , so the probability of is 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 , which remains .
The manual derivative can be checked. If and , for the mean loss equal to half the squared norm over a batch of size , the output gradient is . Then , the gradient with respect to hidden preactivation is because , giving and . 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.
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.
train_steps(2500)train_steps(2500)train_steps(2500)train_steps(2500)train_steps(2500)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.
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 , 0.112 at and 0.045 at . The network performs much worse at low noise. Two effects combine: the factor 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.
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_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 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 , three standard deviations already exceed each center’s distance to the gap, so “far” means outer tails only. At the difference almost disappears (0.088 versus 0.083). At 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 : at , at and at . 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 , Anderson’s (1982) result, used by Song and collaborators, says that the process traversed backward in time solves with . For our VP process, and . With a positive increment advancing toward smaller times, Euler–Maruyama applies
The probability-flow ODE removes noise, and its Euler step is . The factor before compensates for the removed diffusion. In the continuous limit and with the exact score, SDE and ODE have the same marginals . They do not produce the same trajectories, and their finite discretizations have different errors.
The third sampler is the DDPM ancestral step. For , , and , the exact posterior is Gaussian. Replacing by Tweedie’s estimate reduces its mean to , equation 11 of Ho and collaborators written with . We use variance . 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 increasing linearly from to . 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 , is not exactly . Here each sampler starts from exact by first generating 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 . You can check this in the interactive.
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 mode receives about 30% of the particles and 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 . MMD² and the mode split shift only within sampling fluctuations because the difference from exact 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.
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 while difficulty is not. Near , each component’s score is with , and with the SDE term 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 has a mean linear in and fixed covariance, so averaging over the law of given amounts to replacing by , which is exact with the exact score. Its covariance , however, omits uncertainty in given , which would add a term of order 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 estimator of Gretton and colleagues, with RBF kernel 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 . Its spread establishes the scale of sampling fluctuation. Sample size determines power. With 256 points per side, reference fluctuation is of order and hides all errors measured so far. With 1024 it falls to order , while the quadratic cost of three matrices per comparison remains manageable in the browser. Generated samples stop at and are compared with . Population MMD² between and is . It has a closed form. If and are independent in the plane, is normal with covariance , and a Gaussian integral gives with . MMD² between two mixtures is a double sum of those terms, evaluated by the cell. This is the minimum bias due to stopping at .
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.
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("ode")compare("ddpm")With 256 points per side, all six averages, oracle and network for each sampler, lie within the reference range from to . At this size the test distinguishes none of them. With 1024 points, the reference range narrows to 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 samples follow a multinomial distribution and statistic is approximately chi-squared with 3 degrees of freedom, whose 5% threshold is 7.81.
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: for SDE, 166.4 for ODE, and 48.5 for DDPM. All show the same pattern: the mode at receives 17–22% of particles and the mode at 29–32%, while the two -axis modes stay near 25%. This matches the negative mean error in 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 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.
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.
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 tail: roughly 80% of those starting beyond radius 3 escape. The reason is the network’s tail score. At , is nearly and the exact score nearly . The network saw few examples with , around 1% of , and extrapolates a shorter score: at radius 8 its radial component is half the exact one. The ODE drift leaves a particle stationary only when exactly. With and it pushes the particle outward at rate , with nothing to bring it back. For SDE, and for DDPM to first order in , the drift is , which still attracts while . 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 and add 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.
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).
passA diffusion process is approximately reversed by following its score. We obtain the score from a noise predictor by dividing by the noise standard deviation . 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.