Representation Shift
Representation shift is a change in the distribution of a model’s internal vectors — embeddings, encoder outputs, engineered feature blocks — rather than in the raw inputs. It is usually recommended as a monitoring target with a list of tools attached: MMD, energy distance, a classifier two-sample test, run on last month’s embeddings against this month’s.
That recipe has a hole in it, and the hole is the encoder.
Two encoders, one dataset
Comparing stored embeddings with fresh ones is only a measurement of the data if the thing that produced them did not change. When the encoder is refitted between the two, the measurement can include both the refit and data changes.
The experiment below refits a three-component PCA encoder on each month’s data and scores the two encoders on the same query rows. The two embedding distributions, each a cloud of vectors, are compared with the unbiased MMD estimate under a Gaussian kernel whose bandwidth is the median pairwise squared distance: sq computes the pairwise squared distances and mmd2 drops the diagonal terms of the kernel matrix. Retrieval is scored by top_k, the ten nearest corpus rows of each query, and overlap, the mean fraction of those ten that two encoders share. The code blocks in this entry run in order in one session, so later blocks reuse these imports and functions.
import numpy as np
from sklearn.decomposition import PCA
def sq(Z):
s = np.einsum("ij,ij->i", Z, Z)
return np.maximum(s[:, None] + s[None, :] - 2 * Z @ Z.T, 0.0)
def mmd2(X, Y):
Z = np.vstack([X, Y])
d2 = sq(Z)
K = np.exp(-d2 / (2 * np.median(d2[np.triu_indices(len(Z), 1)])))
m, n = len(X), len(Y)
return float((K[:m, :m].sum() - m) / (m * (m - 1))
+ (K[m:, m:].sum() - n) / (n * (n - 1)) - 2 * K[:m, m:].mean())
def top_k(index, query, k=10):
return np.argsort(((query[:, None, :] - index[None, :, :]) ** 2).sum(-1), axis=1)[:, :k]
def overlap(a, b):
return float(np.mean([len(set(x) & set(y)) for x, y in zip(a, b)]) / a.shape[1])
rng = np.random.default_rng(99)
d = 12
basis = np.linalg.qr(rng.normal(size=(d, d)))[0][:4].copy()
for label, scale in (("well separated 3.0 / 1.8 / 1.0 / 0.4", np.array([3.0, 1.8, 1.0, 0.4])),
("nearly tied 2.0 / 2.0 / 1.0 / 0.4", np.array([2.0, 2.0, 1.0, 0.4]))):
def sample(n):
return (rng.normal(size=(n, 4)) * scale) @ basis + 0.3 * rng.normal(size=(n, d))
march, april = sample(4000), sample(4000)
corpus, query = sample(1500), sample(400)
em, ea = PCA(n_components=3).fit(march), PCA(n_components=3).fit(april)
a, b = em.transform(query), ea.transform(query)
print(label)
print(" raw-feature MMD, March vs April %+.6f" % mmd2(march[:800], april[:800]))
print(" embedding MMD, March encoder vs April %+.6f" % mmd2(a, b))
print(" per-component correlation of the two %s"
% " ".join("%+.3f" % np.corrcoef(a[:, k], b[:, k])[0, 1] for k in range(3)))
print(" neighbor overlap, March index + April query %.3f"
% overlap(top_k(em.transform(corpus), a), top_k(em.transform(corpus), b)))
well separated 3.0 / 1.8 / 1.0 / 0.4
raw-feature MMD, March vs April -0.000128
embedding MMD, March encoder vs April -0.002103
per-component correlation of the two +1.000 +1.000 +0.999
neighbor overlap, March index + April query 0.945
nearly tied 2.0 / 2.0 / 1.0 / 0.4
raw-feature MMD, March vs April -0.000307
embedding MMD, March encoder vs April -0.001172
per-component correlation of the two -0.665 +0.651 +1.000
neighbor overlap, March index + April query 0.100
The interesting result is that it depends, and on something specific. With well-separated components the two encoders agree to three decimals and retrieval survives. With two components of nearly equal variance there is no preferred basis inside that plane, refitting returns a rotated one, and neighbor overlap falls to 0.100 — about nine of every ten neighbors from the old result are replaced. That overlap measures result changes, not whether the new neighbors are relevant to the task.
In the nearly tied case MMD is as quiet as in the well-separated one (-0.001172 against -0.002103), yet retrieval breaks. The raw-feature MMD values, also near zero in both cases, show that the data did not change between March and April; only the encoder did. MMD stays low because the refit rotates the embedding inside a plane where the distribution is nearly rotationally symmetric, so the rotated cloud looks like the original. Rotating a single anisotropic distribution can change MMD. Retrieval breaks because new query vectors are compared with an old index in a different coordinate system; applying the same orthogonal rotation to both queries and index preserves Euclidean distances. Check encoder version compatibility as well as embedding distribution tests.
A probe set costs one matrix multiply
The fix is to keep a fixed set of rows, store their embeddings once, and re-embed the same rows with whatever encoder is live. probe_agreement is the mean cosine similarity between each probe’s stored embedding and its re-embedding; it stays at 1 when the encoder is unchanged. The table sets it beside the embedding MMD of a fresh batch for three days.
def probe_agreement(stored, live):
num = np.einsum("ij,ij->i", stored, live)
den = np.linalg.norm(stored, axis=1) * np.linalg.norm(live, axis=1)
return float(np.mean(num / den))
rng = np.random.default_rng(99)
d = 12
basis = np.linalg.qr(rng.normal(size=(d, d)))[0][:4].copy()
scale = np.array([2.0, 2.0, 1.0, 0.4])
def sample(n, drift=0.0):
z = rng.normal(size=(n, 4)) * scale
z[:, 0] += drift
return z @ basis + 0.3 * rng.normal(size=(n, d))
probes = sample(500)
day0 = PCA(n_components=3).fit(sample(5000))
stored = day0.transform(probes)
days = {"day 1, nothing changed": (day0, sample(1500)),
"day 2, the encoder was refitted": (PCA(n_components=3).fit(sample(5000)), sample(1500)),
"day 3, original encoder, data drifted": (day0, sample(1500, drift=0.8))}
print("%-40s %14s %18s" % ("", "embedding MMD", "probe agreement"))
for name, (enc, batch) in days.items():
print("%-40s %14.6f %18.4f"
% (name, mmd2(day0.transform(sample(1500)), enc.transform(batch)),
probe_agreement(stored, enc.transform(probes))))
embedding MMD probe agreement
day 1, nothing changed -0.000084 1.0000
day 2, the encoder was refitted -0.000051 0.1960
day 3, original encoder, data drifted 0.021776 1.0000
The two columns move independently. On day 2 the refit leaves MMD at -0.000051, indistinguishable from the unchanged day 1 at -0.000084, while probe agreement drops from 1.0000 to 0.1960. On day 3 the encoder is the same, so probe agreement stays at 1.0000, and MMD rises to 0.021776 because the data moved. In this example MMD responds to the data and probe agreement responds to the encoder.
Probe changes give evidence of an encoder or preprocessing change on the covered rows. Changes in the embedding distribution can come from the data, the encoder, or both. A finite probe set cannot prove that the encoder is unchanged everywhere; combine probes with version identifiers and deployment records.
Why watch the representation at all
With the encoder pinned down, the case for monitoring there rather than on the raw inputs is simple: the embedding is the layer the model reads. The test is a permutation version of the same MMD statistic: mmd_p builds the kernel matrix once, shuffles which rows count as the first sample, and reports the share of shuffles whose statistic is at least the observed one.
Two shifts of the same size, 0.9 units in the raw feature space, are applied to the same baseline. One is the encoder’s first principal direction, which the encoder keeps; the other is a direction orthogonal to everything the encoder keeps. Each test compares 600 baseline rows with 600 new rows, and the table shows the share of 40 repetitions in which p was below 0.05, for the raw features and for the embedding, beside the mean prediction on the shifted rows.
def mmd_p(X, Y, reps=300):
Z = np.vstack([X, Y])
d2 = sq(Z)
K = np.exp(-d2 / (2 * np.median(d2[np.triu_indices(len(Z), 1)])))
m = len(X)
def stat(i):
a, b = i[:m], i[m:]
return ((K[np.ix_(a, a)].sum() - m) / (m * (m - 1))
+ (K[np.ix_(b, b)].sum() - len(b)) / (len(b) * (len(b) - 1))
- 2 * K[np.ix_(a, b)].mean())
idx = np.arange(len(Z))
s0 = stat(idx)
rng, hits = np.random.default_rng(5), 0
for _ in range(reps):
rng.shuffle(idx)
hits += stat(idx) >= s0
return (hits + 1) / (reps + 1)
rng = np.random.default_rng(1212)
d, n = 10, 600
basis = np.linalg.qr(rng.normal(size=(d, d)))[0]
signal, scale = basis[:4].copy(), np.array([3.0, 1.8, 1.0, 0.4])
def sample(n):
return (rng.normal(size=(n, 4)) * scale) @ signal + 0.3 * rng.normal(size=(n, d))
train = sample(8000)
encoder = PCA(n_components=3).fit(train)
weights = rng.normal(size=3)
def predict(X):
return encoder.transform(X) @ weights
base = sample(n)
step = 0.9
C = encoder.components_
off = basis[7] - C.T @ (C @ basis[7])
off = off / np.linalg.norm(off)
shifts = {"inside what the encoder keeps": step * C[0],
"outside it, same size": step * off}
reps = 40
print("%-32s %12s %13s %16s" % ("shift", "raw MMD", "embed MMD", "mean prediction"))
print("%-32s %12s %13s %16.4f" % ("none", "-", "-", predict(base).mean()))
for name, v in shifts.items():
hit_raw = hit_emb = 0
for _ in range(reps):
fresh_base, fresh_cur = sample(n), sample(n) + v
hit_raw += mmd_p(fresh_base, fresh_cur, reps=199) < 0.05
hit_emb += mmd_p(encoder.transform(fresh_base),
encoder.transform(fresh_cur), reps=199) < 0.05
print("%-32s %11.0f%% %12.0f%% %16.4f"
% (name, 100 * hit_raw / reps, 100 * hit_emb / reps,
predict(base + v).mean()))
shift raw MMD embed MMD mean prediction
none - - -0.1654
inside what the encoder keeps 98% 98% 0.2151
outside it, same size 100% 0% -0.1654
Both shifts are the same size and both are real, and a raw-feature test cannot tell them apart: it flags 98% and 100% of the repetitions. One of them moves the mean prediction by 0.38 when added to the same rows. The other points into the subspace the encoder discards, leaves the mean prediction at the same digits, and the embedding test flags none of the 40 repetitions. Each test compares independently drawn samples, because a permutation test assumes the two samples can be exchanged, which does not hold when one sample is the other shifted by a constant. A rate of 0% in 40 repetitions shows no detectable change in this setting; it is not a proof that the representation is unchanged.
So the ordering is: freeze the encoder and version it like code, keep a probe set to check covered behaviors, and then measure drift where the model reads rather than where the data is stored. Skip the first two and the third measures something, but not the data. The same frozen space is where a row-level off-distribution score is computed, so the encoder version is a dependency of that alarm too.
References
- Gretton, A., Borgwardt, K. M., Rasch, M. J., Schölkopf, B., & Smola, A. (2012). A kernel two-sample test. Journal of Machine Learning Research, 13, 723–773.
- scikit-learn documentation,
sklearn.decomposition.PCA.
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
