A vision-tested uncertainty method meets the geometry of transformer embeddings — and most of the interesting engineering turns out to be about proving the method is doing anything at all.
There is a specific failure mode that haunts anyone who has tried to bolt an uncertainty-quantification module onto a working classifier: the module runs, produces numbers, the numbers get reported, and nobody notices that the module was mathematically inert. Not wrong — inert. It computed something, that something had no effect on any downstream decision, and the reported AUROC was the baseline's AUROC wearing a costume.
This is not hypothetical. It happened in the CIFAR replication that precedes this work, and diagnosing it is what shapes nearly every design decision in the plan described below. The task now is to port DAEDL — density-aware evidential deep learning — from a validated CIFAR implementation to BERT on CLINC150, a 150-class intent classification benchmark with a built-in out-of-scope (OOS) rejection task. The port is not a copy-paste. The geometry of transformer embeddings breaks several assumptions that hold comfortably in vision, and the near-OOD character of the CLINC150 OOS set changes what "success" can even mean.
What follows is a technical account of those breakages, the design decisions taken in response, and — most importantly — the diagnostic machinery built to make a repeat of the inert-density failure structurally impossible rather than merely unlikely.
Standard evidential deep learning replaces the softmax with a Dirichlet distribution over the probability simplex. The network emits evidence parameters, and the Dirichlet concentration α encodes both a prediction (its mean) and a confidence (its total mass α₀). Vacuity, defined as K/α₀, is the headline uncertainty score.
The well-documented weakness of this construction is that α is a direct function of the network logits, and logits are unconstrained on inputs the network has never seen. A feature vector far outside the training manifold can still produce large logits and therefore large evidence — high confidence in a region where the model has no basis for confidence at all. This is the feature-collapse problem, and it is the reason a purely logit-derived uncertainty score cannot be trusted as a distance-aware signal.
DAEDL's answer is to introduce an explicit density term. Fit a Gaussian discriminant model over the penultimate feature space, compute a normalized density estimate p̂ ∈ [0,1] for each input, and use it to modulate the evidence:
The intuition is clean. In high-density regions p̂ ≈ 1 and the rule reduces to standard EDL. In low-density regions p̂ → 0 and exp(z·p̂) → 1 for every class, collapsing to a maximally vacuous Dirichlet regardless of what the logits say. Distance-awareness is injected through the density estimate rather than hoped for from the encoder.
The entire mechanism is hostage to the dynamic range of p̂ on in-distribution data. If the normalizer maps ID densities into a narrow band near 1 — say [0.90, 1.00] — then exp(z·p̂) ≈ exp(z) for essentially every input the model will encounter, and the density term contributes nothing. The scores still compute. The AUROC is still reported. It is vanilla EDL's AUROC.
This is exactly what the reference repository's min-max normalization produced on CIFAR. Min-max is fitted on the min and max of the training log-densities, and log-density distributions have long left tails — a handful of outliers set lo so far below the bulk that the entire bulk compresses into the top decile of the output range.
Two lessons follow, and they structure everything downstream. First, the normalizer is not a preprocessing detail; it is the load-bearing component of the whole method. Second, and more consequentially: a method that can be silently inert requires a test that detects inertness directly, not a metric that happens to look reasonable.
The density model in DAEDL is a Gaussian discriminant analysis over penultimate features. On CIFAR with 512-dimensional features, the CIFAR run already hit condition numbers around 3.5 × 10¹⁴ when fitting per-class covariances — numerically at the edge of what float32 can represent, which is why the density math here moves to float64 on CPU.
BERT is materially worse on three axes simultaneously.
Dimensionality against sample count. Pooled BERT embeddings are 768-dimensional. CLINC150 provides roughly 100 training examples per intent class. A per-class quadratic discriminant model requires estimating a 768×768 covariance matrix from 100 samples — a matrix with ~295,000 free parameters estimated from 76,800 numbers. This is not ill-conditioned; it is unidentifiable. The sample covariance has rank at most 99 in a 768-dimensional space, meaning it is singular by construction and no amount of jitter regularization recovers meaningful structure.
Representation degeneration. Contextual embeddings from pretrained transformers are famously anisotropic — they occupy a narrow cone in the embedding space rather than distributing isotropically. The consequence for density estimation is that the covariance spectrum has a small number of very large eigenvalues and a long tail of near-zero ones. A Gaussian fitted to this geometry devotes almost all of its likelihood mass to a few dominant directions, and the Mahalanobis distance becomes numerically dominated by the whitening of directions that carry almost no variance and almost no signal.
Float32 stiffness on accelerator hardware. Cholesky factorization of a near-singular matrix in float32 fails or, worse, succeeds with garbage. The CIFAR run encountered this on MPS.
Tied covariance as the default, not per-class. A single shared covariance pools all 15,000 training examples into one estimate rather than splitting them 100-per-class. This is precisely the Lee et al. (2018) Mahalanobis detector — the standard, well-conditioned choice in NLP OOD literature — and it is well-conditioned for the right reason: the sample-to-dimension ratio goes from 100:768 to 15000:768.
Preprocessing pipeline: center → PCA(k=128) → whiten. PCA truncation discards the degenerate tail of the spectrum before the covariance is ever fitted, which directly addresses anisotropy rather than papering over it with jitter. Whitening equalizes the retained directions so the Mahalanobis distance is not dominated by the top eigenvalue.
float64 on CPU throughout. The density fit runs on maybe 15k×128 matrices — the compute cost is trivial and numerical stability is not negotiable.
Per-class QDA survives only as an ablation at k ≤ 64, where the sample-to-dimension ratio is at least defensible.
The core of the fit is compact enough to read directly. Note the eigendecomposition-based whitening transform, the pooled residual computation for tied mode, and the escalating jitter grid that fails loudly rather than silently:
def fit(self, feats, labels):
X = np.asarray(feats, dtype=np.float64)
self.mean_ = X.mean(0); Xc = X - self.mean_
cov = (Xc.T @ Xc) / max(len(Xc) - 1, 1)
w, V = np.linalg.eigh(cov) # spectrum of the pooled cov
order = np.argsort(w)[::-1]
w, V = np.clip(w[order], self.cfg.min_var, None), V[:, order]
k = self.cfg.pca_dim or X.shape[1]
self.T_ = V[:, :k] / np.sqrt(w[:k]) # PCA + whitening in one map
Z = Xc @ self.T_
if self.cfg.cov_mode == "tied":
R = np.concatenate([Z[y == c] - self.mu_[i] # pool ALL residuals
for i, c in enumerate(self.classes_)])
S = (R.T @ R) / max(len(R) - len(self.classes_), 1)
self.chol_, self.jitter_ = self._chol(S)
The theoretical justification for density-based OOD detection over neural features assumes something specific about the feature extractor: that it is approximately bi-Lipschitz, meaning it neither collapses distinct inputs to the same point nor arbitrarily expands small input differences. Without this property, a feature-space density estimate says nothing reliable about input-space typicality — two semantically unrelated utterances can land in the same feature neighborhood and receive identical density scores.
Convolutional networks can be made approximately bi-Lipschitz through spectral normalization plus residual connections; this is the foundation of SNGP and related distance-aware architectures. Transformers are considerably harder. Self-attention is a data-dependent mixing operation whose Lipschitz constant depends on the input; LayerNorm is a projection onto a sphere that destroys magnitude information by design; and the residual-plus-normalization stack composes these effects across twelve layers. Enforcing distance preservation through the full BERT stack is not a solved problem, and naive spectral normalization inside the encoder tends to damage accuracy substantially.
Spectral normalization is applied to a Linear(768 → 256) bottleneck head only, leaving the encoder untouched. Critically, the bottleneck carries no nonlinearity by default — the feature the GDA sees is an affine map of the pooled embedding.
This has a specific consequence worth stating plainly: an affine transform of a Gaussian is Gaussian. By keeping the bottleneck linear, the feature distribution that the Gaussian discriminant model is asked to fit remains as close to its Gaussian modeling assumption as the pooled embedding itself was. Inserting a ReLU would fold the distribution against the origin and introduce exactly the kind of non-Gaussianity that GDA handles poorly. ReLU and tanh are retained as ablations, not defaults.
One further decision deserves emphasis because it inverts the usual instinct. The classifier head is deliberately left un-normalized, so logit magnitude is free to grow. The reasoning is diagnostic rather than architectural: the CIFAR investigation established that the exp(z · p̂) mechanism is hostage to logit scale — if z is large, then even a substantial reduction in p̂ produces a small relative change in exp(z·p̂) compared to the dynamic range of z itself. Constraining logit scale would mask this interaction. The plan instead leaves it unconstrained and measures it, which is the only way to learn anything about it.
The natural benchmark anchor here is the SNGP paper (Liu et al., NeurIPS 2020), which includes a BERT-on-CLINC150-OOS experiment. It is the canonical distance-aware-transformer result on this exact dataset and provides both a deterministic-BERT baseline row and a distance-aware target.
This bottleneck is conceptual rather than numerical, and it is the one most likely to be underestimated by anyone arriving from vision benchmarks.
CIFAR-10 against SVHN is a far-OOD problem. The two datasets differ in subject matter, capture conditions, color statistics, and low-level texture. A density model over learned features has an easy time separating them because they are genuinely separated in almost any reasonable representation.
CLINC150's out-of-scope set is fluent, natural, well-formed English — conversational utterances that simply do not correspond to any of the 150 supported intents. Relative to a BERT encoder pretrained on a substantial fraction of the internet, these utterances are emphatically in-distribution at the representation level. They are out-of-scope with respect to the task, not out-of-distribution with respect to the encoder.
Three consequences follow directly. Raw density gaps will be smaller, so normalizer design matters more, not less — a normalizer that squashes a large gap is wasteful; a normalizer that squashes a small gap is fatal. Validation-based selection becomes essential rather than nice-to-have, since the margins between configurations will be narrow enough that eyeballing will not resolve them. And the honest claim to target shifts: beating maximum-softmax-probability by a wide margin is not a realistic goal on near-OOD intent detection. Beating it reliably across seeds is. That framing is stated up front in the plan rather than discovered retroactively, which is the difference between a result and a rationalization.
Given the diagnosis, the interventions divide into two categories: fixing the normalizer so the density signal survives into α, and building an automated test that refuses to let an inert configuration reach a results table.
Three normalizers are made pluggable, each fitted on training log-densities only — a detail that matters for leak-freedom, since fitting on validation would contaminate the selection process the entire experimental design depends on.
| Normalizer | Mechanism | Role |
|---|---|---|
| minmax | Linear rescale between train min and max | reference-faithful Retained purely for comparability with the source repository. This is the one that failed on CIFAR. |
| qsigmoid | Logistic centered at the 5th percentile, scaled by (q50−q05)/2 |
recommended for mul Anchors the transition on quantiles rather than extrema, so the heavy left tail cannot compress the bulk. ID mass sits near 1; low-density inputs fall toward 0. |
| ecdf | Empirical rank against sorted train log-densities | pairs with add_log Distribution-free by construction. Immune to tail geometry entirely, at the cost of discarding magnitude information. |
The quantile-sigmoid deserves a note on why it addresses the specific failure. Min-max is a function of two order statistics — the extremes — which are precisely the least stable summaries of a heavy-tailed distribution. The quantile-sigmoid is a function of the 5th and 50th percentiles, which are robust. Where min-max asks "how far is this point between the most and least dense training examples," qsigmoid asks "is this point below the density level that only 5% of training data falls under," which is the question the mechanism actually needs answered.
The second intervention is a new combination rule that sits alongside the DAEDL-faithful multiplicative one. This is the most substantive theoretical contribution in the plan:
The distinction has real teeth. In the multiplicative rule, p̂ multiplies each logit, so the relative ordering of logits can change when p̂ varies — a low-density input can have its argmax flipped, meaning the density term can change the prediction, not just the confidence. On in-distribution data this is a pure accuracy liability.
In the additive-log rule, λ(p̂ − 1) is a scalar added identically to every logit. Since argmax is invariant to adding a constant to all entries, the prediction is provably unchanged. What does change is α₀, which is scaled by e^{λ(p̂−1)} — a factor of 1 when p̂ = 1 and shrinking exponentially as density falls. Density is injected into evidence mass only.
def scale_alpha(logits, phat, mode="mul", lam=5.0, clamp=15.0):
z = logits.clamp(-clamp, clamp)
p = phat.to(z.dtype).unsqueeze(-1)
if mode == "mul": # DAEDL-faithful: can flip predictions
return torch.exp(z * p)
if mode == "add_log": # prediction-preserving: scales alpha0 only
return torch.exp(z + lam * (p - 1.0))
The add_log rule decouples two things that DAEDL conflates: what the model predicts and how much the model should be believed. For deployment in a rejection-gated system — which is the eventual target — this decoupling is exactly what you want. The classifier's accuracy on in-scope traffic is preserved by construction, and the density signal operates purely on the accept/reject decision. It cannot trade accuracy for detection, because it has no mechanism to do so.
It also makes the ablation cleanly interpretable. Any change in in-scope accuracy under add_log is a bug, not a tradeoff. That is a strong invariant to be able to assert.
The normalizer redesign makes inertness less likely. The materiality gate makes it detectable, which is the stronger property. This is a diagnostic that compares the plain α against the density-scaled α and asks directly: did anything change?
a0p = alpha_plain.sum(-1) # evidence mass, no density
a0s = alpha_scaled.sum(-1) # evidence mass, density-scaled
flip = (alpha_plain.argmax(-1) != alpha_scaled.argmax(-1)).float().mean()
rel = np.median(np.abs(a0s - a0p) / (a0p + 1e-12))
rho = spearmanr(a0p, a0s).statistic
rep["materiality"] = {
"flip_rate": flip,
"median_rel_delta_alpha0": rel,
"spearman_alpha0": rho,
# INERT == the CIFAR failure mode: scaled alpha ranks identically
"density_effect": "INERT" if (rho >= 0.999 and rel < 0.05) else "ACTIVE",
}
The Spearman correlation is the load-bearing statistic. AUROC is a rank statistic: it depends only on the ordering of scores, not their magnitudes. If ρ(α₀ᵖˡᵃⁱⁿ, α₀ˢᶜᵃˡᵉᵈ) ≥ 0.999, then the density-scaled scores induce essentially the same ordering as the unscaled ones, and any AUROC computed from them is arithmetically guaranteed to match vanilla EDL's. That is what "inert" means, made operational. The median relative change in α₀ is a second check catching cases where a uniform multiplicative rescale preserves rank while genuinely shifting the confidence scale.
The gate is then wired into the selection procedure with real authority: a configuration flagged INERT is disqualified from the headline table even if its AUROC looks excellent. This is the methodological centerpiece. It converts a class of error that was previously caught only by a suspicious researcher manually inspecting intermediate values into an automated precondition that a result must satisfy before it is allowed to exist.
Two additional design commitments deserve mention because they generalize well beyond this project.
A single orientation convention, unit-tested. Every uncertainty score in the codebase is defined so that higher means more out-of-scope, and OOS is the positive class in every metric computation. This sounds trivial. It is not: the CIFAR run contained a bug where a variable named auroc_epis was computed from the aleatoric score. Sign and orientation errors in uncertainty code are insidious because a flipped score often still produces a plausible-looking AUROC — sometimes even a good one, if the flipped quantity happens to be anti-correlated with the target. The fix is a test that constructs a deliberately confident logit vector and a deliberately unsure one and asserts the ordering for every score in the registry:
def test_orientation():
conf = torch.tensor([[8.0, 0.1, 0.1]]) # confident
unsure = torch.tensor([[0.4, 0.3, 0.3]]) # unsure
for k, v in scores_from_logits(unsure).items():
assert v > scores_from_logits(conf)[k], k # higher = more OOS
A validation OOS split that actually exists. The original pipeline silently discarded oos_val, keeping only oos_test. This is described in the plan as the single most important fix, and the reasoning is worth spelling out for the applied-science reader: every decision the method requires — which normalizer, which combination rule, what value of λ, where to put the rejection threshold, whether the uncertainty signal is learning at all during training — is a decision that needs OOS data to make. With only oos_test available, each of those decisions leaks test information into the reported result. The 100 held-out OOS validation utterances are what make the final number honest.
The experimental plan is structured as a sequence of gated phases, with numeric exit criteria fixed in advance. The intent is to make it impossible to slide into an unfalsifiable "it's almost working" state.
pca_dim × cov_mode, selected on raw density AUROC before any normalizer — so a dead representation cannot be rescued by normalization tricks. C2 (normalizer × rule): selected on daedl_vacuity val AUROC, with INERT configs disqualified outright. C3 (inclusion): DAEDL enters the headline table only if its val AUROC advantage exceeds the pooled 5-seed standard deviation.return_hidden_states passthrough in the model, empty placeholder modules, and the oos_val split that exit-threshold calibration will need. The deliverable is a compute–accuracy–OOS-safety Pareto curve.If C1 fails, or C3 fails, or the calendar runs out, the headline reverts to CE+MSP / CE+Mahalanobis / EDL, and DAEDL is written up as a rigorously diagnosed negative result: the density term is inert or ineffective on near-OOD intent detection under normalizers X, Y, Z, with diagnostics.json numbers attributing the cause.
This is worth stating plainly for the business-side reader: a negative result with this level of forensic instrumentation is more valuable than a marginal positive result without it. It tells you something durable about when the method works — and it tells you the measurement apparatus is trustworthy, which is a prerequisite for believing any future positive result from the same pipeline. Demonstrating the same diagnostic discipline twice, across two modalities, is the actual contribution.
It is worth situating this work against the broader critique of evidential deep learning. Recent theoretical analysis — most pointedly Shen et al. (NeurIPS 2024) — establishes that single-model EDL does not learn statistically meaningful epistemic uncertainty; its optimal meta-distribution is sample-size-independent, and the method is better characterized as an energy-based OOD detector wearing Dirichlet clothing. Vacuity does not vanish with more data, as genuine epistemic uncertainty must.
The work described here is, in an important sense, a constructive response to that critique rather than a refutation of it. If EDL's uncertainty is fundamentally a distance-to-training-distribution signal, then the honest engineering move is to make that distance signal explicit, well-conditioned, and measurable — which is exactly what a properly fitted density term does. DAEDL is not trying to rescue the Bayesian interpretation. It is trying to supply, through an external density model, the distance-awareness that the logit-derived evidence cannot provide on its own.
Seen this way, the materiality gate is not just a bug catcher. It is a direct empirical test of whether the density contribution is real or whether the reported performance is, once again, the underlying OOD detector's performance under a different name. That is precisely the question Shen et al.'s analysis says one should be asking of every EDL result.
And the near-OOD framing sharpens it further. On far-OOD benchmarks, almost any distance signal works, which is why so many methods report strong CIFAR→SVHN numbers and why those numbers discriminate poorly between approaches. Fluent, task-irrelevant English against a pretrained encoder is the regime where distance-awareness has to be earned. It is also, not incidentally, much closer to what deployment actually looks like: the queries that break a production intent classifier are rarely gibberish. They are well-formed requests for something the system was never built to do.