NeurIPS 2026Coming to NeurIPS?Explore papers, orals & directions

Robustify Transformers with Robust Kernel Density Estimation

Xing Han, Tongzheng Ren, Tan Minh Nguyen, Khai Nguyen, Joydeep Ghosh, Nhat Ho

TL;DR

Standard dot-product self-attention in Transformers can be framed mathematically as Nadaraya-Watson (NW) kernel regression, which makes it inherently fragile to corrupted or anomalous inputs. By replacing vanilla Kernel Density Estimation (KDE) with Robust KDE (RKDE) and Scaled Projection KDE (SPKDE) in the attention computation, the authors provide a principled way to down-weight outliers across both vision and NLP tasks without adding new parameters or changing model backbones.

What Problem Does This Paper Address?

While Transformers dominate language, vision, and reinforcement learning, they remain vulnerable to adversarial perturbations, out-of-distribution shifts, and corrupted tokens. Prior attempts to fix this (especially in vision) typically modify the network architecture—such as adding fully connected layers for position-aware attention—which introduces extra parameters and breaks causality or bidirectional properties needed for language modeling.

The authors view attention through the lens of non-parametric statistics: normalized softmax self-attention corresponds to Nadaraya-Watson regression based on Gaussian kernel density estimation (KDE). In statistics, vanilla KDE is notoriously sensitive to outliers because it equally weights squared errors in a reproducing kernel Hilbert space (RKHS). When adversarial or contaminated tokens enter the context, they disproportionately distort the estimated density and compromise attention outputs.

Methods

The paper reimagines self-attention by solving robust density estimation formulations in the RKHS:

  • Transformer-RKDE: Replaces the squared $L_2$ loss in the RKHS regression objective with robust M-estimator loss functions (e.g., Huber loss or Hampel loss). Instead of giving equal weight ($1/N$) to each token, sample weights are iteratively adjusted via the Kernelized Iteratively Re-weighted Least Squares (KIRWLS) algorithm: $$\hat{\mathbf{h}}_i = \frac{\sum_{j} \mathbf{v}_j \, \omega_j^{\text{joint}} \, k_\sigma(\mathbf{q}_i - \mathbf{k}_j)}{\sum_{j} \omega_j^{\text{marginal}} \, k_\sigma(\mathbf{q}_i - \mathbf{k}_j)}$$ In practice, a single-step iteration of KIRWLS is sufficient to down-weight anomalous key-value pairs without major computational overhead.

  • Transformer-SPKDE: Uses Scaled Projection KDE, scaling the empirical KDE by $\beta > 1$ and projecting it onto the nearest weighted KDE within the convex hull of RKHS kernel functions via quadratic programming (QP). This truncates weights for extreme anomalies while boosting high-density regions.

  • Architecture-Agnostic Plug-in: No extra parameters are added to the Transformer. The method merely computes reweighted attention maps using the Gram matrix directly via the kernel reproducing property.

Datasets

  • WikiText-103: Evaluated under standard language modeling conditions as well as an adversarial "word swap" attack (where keywords are replaced with a generic token using the TextAttack library).
  • ImageNet (ILSVRC-2012): Evaluated on clean validation data and under white-box/black-box adversarial attacks (FGSM, PGD, and SPSA).
  • ImageNet-C: Evaluated against 15 algorithmically generated common visual corruptions across 5 severity levels (measured via mean Corruption Error, mCE).

Key Insights and Ideas

  • The Attention–KDE Equivalence: Self-attention is fundamentally non-parametric regression. Acknowledging this connection allows decades of robust statistics literature to directly guide architectural improvements.
  • Single-Step KIRWLS Suffices: While KIRWLS is theoretically iterative, running just a single step strikes the optimal balance between defensive robustness and training speed (0.43 s/it vs 0.35 s/it for baseline DeiT).
  • Unified Cross-Modal Defense: Because the defense operates directly on inner products in the attention matrix rather than modality-specific spatial biases, the same formulation protects both token sequences in language models and patch embeddings in vision transformers.

Key Results

  • Adversarial Image Classification (DeiT-Tiny Backbone):
  • Under untargeted FGSM attack ($\epsilon = 1/255$), DeiT-SPKDE improves top-1 accuracy from 52.61% (baseline DeiT) to 56.03% (beating the specialized robust vision transformer, RVT, at 53.67%).
  • Under PGD (20 steps), DeiT-SPKDE achieves 44.51% vs. 41.84% for baseline DeiT and 43.39% for RVT.
  • Robustness gains widen as perturbation budgets increase.
  • Robust Language Modeling (WikiText-103):
  • On clean data, Transformer-SPKDE slightly improves validation/test perplexity to 33.05 / 34.18 (vs. 33.52 / 34.59 for standard Softmax).
  • Under the Word Swap attack, Transformer-SPKDE dramatically preserves perplexity at 54.97, compared to 74.56 for standard Softmax attention.

Limitations and Future Work

  • Inference Overhead: While 1-step RKDE introduces only modest latency, SPKDE requires solving a quadratic program per layer, increasing iteration time substantially (1.45 s/it vs 0.35 s/it on DeiT).
  • Hyperparameter Sensitivity: The robustness threshold parameters (such as Huber cut-off $a$ or SPKDE scaling $\beta$) must be tuned depending on the expected contamination level.
  • Future Directions: The authors emphasize developing faster, approximate QP solvers or closed-form weight predictors to scale robust density estimation to very long sequence lengths and massive foundation models.

Summary updated

BibTeX
@inproceedings{han2023robustify,
  author = {Xing Han and Tongzheng Ren and Tan Minh Nguyen and Khai Nguyen and Joydeep Ghosh and Nhat Ho},
  title = {{Robustify Transformers with Robust Kernel Density Estimation}},
  booktitle = {International Conference on Learning Representations},
  year = {2023},
  url = {https://openreview.net/forum?id=2Fb-h04mt5I},
}

Loading related content...

Figure