Back to paper library
arXiv 2023IEEE TIFS 2024Face anti-spoofingPaper notes

S-Adapter

Real Notebook

Original paper

S-Adapter: Generalizing Vision Transformer for Face Anti-Spoofing with Statistical Tokens

Paper authors

Rizhao Cai · Zitong Yu · Chenqi Kong …

Show all 7 authors

Rizhao Cai · Zitong Yu · Chenqi Kong · Haoliang Li · Changsheng Chen · Yongjian Hu · Alex Kot

First submitted to arXiv
arXiv:2309.04038
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{faceantispoofingsadapter2023,
  title = {{S-Adapter: Generalizing Vision Transformer for Face Anti-Spoofing with Statistical Tokens}},
  author = {Rizhao Cai and Zitong Yu and Chenqi Kong and Haoliang Li and Changsheng Chen and Yongjian Hu and Alex Kot},
  year = {2023},
  eprint = {2309.04038},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2309.04038}
}
On this page

Adapter is a lightweight model adjustment technique that typically adds additional parameters to a pre-trained Transformer model. These parameters can be fine-tuned for specific tasks without needing to retrain the entire model.

If Transformers are the main protagonists in recent computer vision research, then adapters are the role adjusters that bridge tasks.

Defining the Problem

Looking at the face anti-spoofing (FAS) models so far, it’s clear how difficult they are.

Not only do you need to determine "is this face real or fake," but it must be stable enough. At the very least, it shouldn't fail simply because the lighting changed, the camera switched, or a new type of attack is used.

The model does not usually fail because it is too weak, but because the “world” it grows used to during training is too small. Imagine taking thousands of photos of real faces indoors, then deploying the model where someone scans their face with a phone under the blazing sun: it falls apart. No matter how much we fine-tune or stack models, domain shift can still undo generalization.

Thus, various solutions have emerged: Some use adversarial learning for style transfer, some use meta-learning to simulate unseen scenarios, while others try to compress real faces closer and spread fake faces further apart. But these methods still fall short when it comes to generalization, particularly in zero-shot testing.

Then came ViT (Vision Transformer), and people were excited.

After all, the attention mechanism in Transformers handles long-range information well, and the architecture is flexible, seemingly perfect for tasks that involve strong environmental variations.

But then another issue arises.

While we can fine-tune a pre-trained ViT model on ImageNet, it indeed performs slightly better than CNN-based models, but just "slightly." Sometimes, in few-shot or even zero-shot conditions, the ViT performs worse than CNN-based baselines.

There might be a more fundamental problem here:

  • Transformers can see far, but can they see fine details?
  • Can they recognize subtle textures, local defects, and weaknesses left by attack mediums?

Or perhaps, we’ve assumed too quickly that Transformers can understand these "things beyond style"?

Solving the Problem

The first step in applying ViT to FAS is usually: fine-tuning a pre-trained ImageNet model.

To update fewer pretrained parameters during FAS fine-tuning, we can insert small Adapter modules, freeze the original ViT weights, and train the newly added task-specific parameters.

This approach is called Efficient Parameter Transfer Learning (EPTL), and methods like Adapter, LoRA, and Prompt-tuning all fall into this category.

In ViT, we can simplify the process of each block as the following inference process (ignoring LayerNorm and skip connections):

Y=WiMLP(WiMSA(X))Y = W_i^{\text{MLP}}(W_i^{\text{MSA}}(X))

Here, XX and YY are the input and output tokens of a transformer block, MSA represents multi-head self-attention, and MLP is the multi-layer perceptron. If we use an Adapter, the structure becomes:

Y=AiMLP(WiMLP(AiMSA(WiMSA(X))))Y = A_i^{\text{MLP}}(W_i^{\text{MLP}}(A_i^{\text{MSA}}(W_i^{\text{MSA}}(X))))

Here AiMSAA_i^{\text{MSA}} and AiMLPA_i^{\text{MLP}} are the inserted Adapters. The original ViT weights WW are frozen while the Adapters and other newly added parameters are updated, reducing the number of parameters to fine-tune.

However, this Adapter structure works well in natural language tasks but struggles in FAS.

The reason is not hard to understand: General Adapters use linear layers, which lack the inductive bias of spatial structure.

But FAS depends heavily on local details—image artifacts, blurred edges, and reconstruction noise. Global attention can learn local cues, yet a standard linear Adapter does not explicitly model neighboring patches. That is the bias the authors want to add.

Model Architecture

To help the Transformer capture local texture features, the authors propose S-Adapter.

The inspiration comes from traditional texture analysis methods like Local Binary Pattern (LBP), as shown in the figure (a) above.

LBP does not classify raw pixel values directly. It extracts local texture patterns and then counts them in histograms. Such statistics can be more robust to changes in lighting and materials, which is why they were used in earlier face analysis and anti-spoofing work.

The design of S-Adapter is to translate this logic into the Transformer world:

Enable ViT tokens to learn statistics and extract spatial distribution features from local textures.

The overall structure is as follows:

The entire module is divided into two stages: Token Map Extraction and Token Histogram Extraction.

Token Map Extraction

In the FAS (Face Anti-Spoofing) scenario, the key to detecting attacks often lies in local details.

These details could be blur, edge artifacts, small texture anomalies caused by re-capturing, and such features are difficult for the global attention mechanism of Transformers to capture.

ViT represents patch tokens as a one-dimensional sequence; a general linear Adapter does not directly receive their original two-dimensional neighborhood. Reshaping makes that neighborhood explicit for convolution, while retaining token order and position.

Therefore, the first step is to design a process that restores the spatial properties of tokens:

  • Given the input tokens X∈RNP×CX \in \mathbb{R}^{N_P \times C}, where NPN_P is the number of patch tokens (class token is ignored) and CC is the embedding dimension; the illustrated configuration first reduces the channels from 768 to 8;
  • Reshape it to XR∈RH×W×CX_R \in \mathbb{R}^{H \times W \times C}, where H×W=NPH \times W = N_P;
  • Then permute the dimensions to XM∈RC×H×WX_M \in \mathbb{R}^{C \times H \times W}, similar to a CC-channel image.

Next, use a 2D convolution layer WConvW_\text{Conv} to extract local features:

Z=WConv(XM)Z = W_{\text{Conv}}(X_M)

This introduces an explicit spatial inductive bias, helping the Adapter attend to local information.

To make the model more sensitive to local changes, the authors introduce a Center Difference (CD) operation:

  • For each token ZnZ_n, compute the difference with its surrounding neighbors PnP_n;
  • Weighted sum using the convolution kernel weights ω(p)\omega(p):
Zng=∑p∈Pnω(p)⋅(Zp−Zn)Z^g_n = \sum_{p \in P_n} \omega(p) \cdot (Z_p - Z_n)

This results in ZgZ^g, which captures fine-grained local gradient features, especially for subtle texture changes.

Finally, the original feature ZZ is fused with the gradient feature ZgZ^g to form a new token map:

Z∗=(1−θ)Z+θZgZ^* = (1 - \theta) Z + \theta Z^g

where θ\theta controls the fusion ratio. This allows even ViT to incorporate local feature sensitivity similar to CNN.

Token Histogram Extraction

Even with added local features, domain shift (cross-device, cross-lighting) still leads to instability in model performance.

The reason is that local pixel values are still easily affected by environmental factors.

Thus, the second step is to further statistically analyze these local features by computing a differentiable histogram for each small region.

Intuitively, this means:

  • Soft binning a local window around each patch token;
  • Obtaining a statistical vector instead of a single pixel value;
  • Allowing the model to learn the overall structural distribution of local regions, rather than individual point values, enhancing domain stability.

The computation process is as follows:

Let μc\mu_c be the center and γc\gamma_c control response width. Larger ∣γc∣|\gamma_c| produces a narrower response, so it acts as an inverse scale rather than the width itself. Using a centered 3×33\times3 neighborhood N={−1,0,1}2\mathcal{N}=\{-1,0,1\}^2:

ZHistc,h,w=19∑(j,k)∈Nexp⁡(−γc2(Zc,h+j,w+k∗−μc)2)Z_{\text{Hist}}^{c,h,w} = \frac{1}{9} \sum_{(j,k)\in\mathcal{N}} \exp \Bigl( -\gamma_c^2 (Z^*_{c,h+j,w+k} - \mu_c)^2 \Bigr)

where:

  • J=K=3J = K = 3, i.e., a 3x3 convolution window;
  • stride = 1, padding = 1, ensuring the size remains unchanged.

The soft binning ensures that values closer to the bin center contribute more, and values farther away contribute less, making it differentiable.

Breaking it down further:

ZHistc,h,w=19∑(j,k)∈Nexp⁡(−Uc,j,k2)Z_{\text{Hist}}^{c,h,w} = \frac{1}{9} \sum_{(j,k)\in\mathcal{N}} \exp (-U_{c,j,k}^2) Uc,j,k=γc(Zc,h+j,w+k∗−μc)U_{c,j,k} = \gamma_c (Z^*_{c,h+j,w+k} - \mu_c)

Uc,j,kU_{c,j,k} can be implemented with two channel-wise 1×11\times1 affine transforms. A dense convolution with every weight set to one would mix channels and would not implement this expression:

  • First layer WConv1W_{\text{Conv1}}: the weights are fixed to 1, the bias is learnable (corresponding to −μ-\mu);
  • Second layer WConv2W_{\text{Conv2}}: the bias is fixed to 0, and the weights are learnable (corresponding to γ\gamma).

This design allows both the bin center and bin width to be automatically adjusted through training.

Finally, in the illustrated ViT-Base configuration, ZHistZ_{\mathrm{Hist}} is reshaped into NP×8N_P\times8 tokens, projected back to NP×768N_P\times768, and fused with the original tokens. These are dimensions of the learned features of neighboring patch tokens, rather than a histogram of raw pixels within each patch.

Gram Matrix

In the context of deep learning, we can roughly classify image features into two categories:

  • Content: Essential information related to the task, such as texture flaws, blurred edges, and reorganization traces.
  • Style: Environmental style features related to the image capture, such as lighting, saturation, color shifts, and noise distribution.

Many previous methods have attempted to use adversarial learning for feature disentanglement to separate these two types of information. However, these methods often struggle with instability and convergence, particularly in cross-domain tasks where convergence speed and stability are major challenges.

This paper adopts a more intuitive approach: Since we know style can be represented using a Gram matrix, let's directly regularize the Gram matrix.

First, the authors define the Gram matrix for the token map Z∈RC×H×WZ \in \mathbb{R}^{C \times H \times W} as follows:

G(Z)k,k′=1CHW∑h=1H∑w=1WZk,h,w⋅Zk′,h,wG(Z)_{k,k'} = \frac{1}{CHW} \sum_{h=1}^H \sum_{w=1}^W Z_{k,h,w} \cdot Z_{k',h,w}

Here Zk,h,wZ_{k,h,w} is the value of channel kk at spatial position (h,w)(h,w). The Gram matrix measures uncentered inner products between channels as a proxy for this image's “style”; it is not a covariance matrix.

In the authors' design, the goal is not to enforce uniformity across all image styles but to regularize the style consistency between bonafide (genuine) samples.

This design has two advantages:

  1. It places no direct Gram-alignment constraint on attack samples, preserving differences useful for separating real from spoofed faces.
  2. It follows the authors' modeling assumption: styles of bonafide samples from different sources should be brought closer, while attack appearances may differ.

Given bonafide token maps from two domains, ZD1Z_{D1} and ZD2Z_{D2}, the style regularization loss is defined as:

LTSR=∥G(ZD1)−G(ZD2)∥F2\mathcal{L}_{\text{TSR}} = \left\| G(Z_{D1}) - G(Z_{D2}) \right\|_F^2

The loss encourages bonafide samples from two source domains to have closer Gram matrices. Whether that makes the model focus more on content cues still has to be tested.

The following diagram illustrates this design logic:

The style of bonafide samples from different domains is aligned, but no additional constraints are applied to spoof attack samples, preserving their distinguishability.

In addition to TSR, the model still needs to distinguish between real and fake. Therefore, the authors use the common Binary Cross-Entropy (BCE) loss:

LBCE=−[y⋅log⁡(y^)+(1−y)⋅log⁡(1−y^)]\mathcal{L}_{\text{BCE}} = - \left[ y \cdot \log(\hat{y}) + (1 - y) \cdot \log(1 - \hat{y}) \right]

For multiple source domains, the authors average over every pair of bonafide domains, using token maps from the last Transformer block. If P={(i,j):i<j}\mathcal{P}=\{(i,j):i<j\} is the set of pairs, its size ∣P∣|\mathcal{P}| is the averaging denominator:

LTSRavg=1∣P∣∑(i,j)∈P∥G(ZDi)−G(ZDj)∥F2\mathcal{L}_{\text{TSR}}^{\text{avg}} = \frac{1}{|\mathcal{P}|} \sum_{(i,j)\in\mathcal{P}} \left\| G(Z_{D_i}) - G(Z_{D_j}) \right\|_F^2

Finally, the total loss is:

Ltotal=LBCE+λ⋅LTSRavg\mathcal{L}_{\text{total}} = \mathcal{L}_{\text{BCE}} + \lambda \cdot \mathcal{L}_{\text{TSR}}^{\text{avg}}

λ\lambda controls how strongly style regularization influences training. In the BCE expression, y=0y=0 denotes bonafide and y=1y=1 denotes spoof, and y^\hat y is the predicted spoof probability.

Discussion

In this section, let's take a look at how S-Adapter performs under various experimental settings.

The authors conducted four different types of evaluations:

  • Intra-Domain Testing (Training and testing within the same dataset)
  • Cross-Domain Testing (Testing across datasets)
  • Few-Shot Cross-Domain Testing (Testing with a small amount of target data)
  • Unseen Attack Testing (Testing with attack types that the model has not seen before)

The datasets used for evaluation include CASIA-FASD, Replay Attack, MSU MFSD, OULU-NPU, and SiW-M. The evaluation metrics include HTER, ACER, EER, AUC, and TPR at FPR = 1%.

Intra-Domain Testing

The authors compare the performance of existing methods on the four standard protocols of the OULU-NPU dataset, as shown in the table below:

In ACER, S-Adapter-TSR has the lowest listed result on P1, P3, and P4. Its P2 result is 0.8%, above EPCR's 0.6%. It performs well under most of these within-dataset protocols, though this table does not separate the effects of local features from those of the histogram.

However, looking at Intra-Domain alone is not enough to prove generalization capability.

Cross-Domain Testing

The Cross-Domain testing uses the classic MICO protocol (leave-one-out testing between the four datasets: CASIA-FASD, Replay-Attack, MSU-MFSD, OULU-NPU).

The results are shown in the table below:

For both HTER and AUC, S-Adapter-TSR outperforms the table's ViT† baseline in all four leave-one-out directions, as well as the listed SSAN-R and MetaPattern results. ViT† excludes supplementary CelebA-Spoof data in this comparison, so it should be read under this table's training setup.

This echoes the design's central idea: fine-tuning ViT for FAS also calls for better local recognition and resistance to changes in style.

Limited Source Domains Testing

In practice, collecting cross-domain datasets is not an easy task.

Therefore, the authors further test whether the model can maintain cross-domain performance when only two source datasets are used for training (e.g., MSU + Replay).

The results are shown in the table below:

Even with two sources, S-Adapter-TSR has the lowest HTER (17.93%) and highest AUC (89.56%) on M&I → C. On M&I → O, its 19.76% HTER and 86.87% AUC are slightly behind AMEL's 19.68% and 87.01%. The advantage in the first limited-source setting should therefore not be generalized to both.

Ablation Experiments

Finally, the authors conduct ablation experiments to specifically examine the contributions of S-Adapter and TSR.

Effectiveness of S-Adapter Components

First, the authors tested different versions of S-Adapter:

  • S-Adapter (Full version)
  • S-Adapter w/o hist (Removed histogram layer)
  • S-Adapter w/o hist(θ=0) (Removed both histogram and gradient extraction)

The experimental results are shown in the figure below:

From the results, we can see that:

  • The full version of S-Adapter performs best in HTER across the four cross-domain scenarios.
  • Removing the histogram (w/o hist) causes a significant performance drop.
  • Removing gradients as well (θ=0) is usually worse, though the O-domain exception below matters.

This confirms that statistical features (histogram) and local gradients make substantial contributions to cross-domain recognition.

However, in the special case of C&I&M to O, adding gradients to the version without a histogram actually increases HTER slightly.

The authors speculate that this is due to the higher resolution of the OULU-NPU dataset, while I, C, and M sources have lower resolutions, causing inconsistent gradient features across resolutions. The histogram statistical layer helps smooth this discrepancy, thus maintaining stable performance.

Histogram's Enhancement Effect on Vanilla Adapter

To verify the universality of histograms, the authors also added CDC layers and Histogram layers to the standard vanilla adapter.

The results are shown below:

It can be seen that:

  • After adding CDC, HTER decreased (HTER lower is better).
  • Adding Histogram further improved the performance.

Across these four cross-domain tests, the histogram layer further reduces HTER even when added to a standard Adapter, so its benefit is not confined to the complete S-Adapter tested here.

TSR Module and λ Hyperparameter

Next, let's look at the ablation of Token Style Regularization (TSR).

The authors set different values of λ, from 0 to 1, and observed the impact on HTER, as shown in the figure below:

It can be observed that:

  • The best λ\lambda differs across the four curves. For C&I&O → M, HTER at λ=0.05\lambda=0.05 is actually higher than at λ=0\lambda=0.
  • A large λ\lambda can also raise HTER; for example, C&M&I → O is clearly worse at λ=1.0\lambda=1.0 than at intermediate values.
  • The authors suggest starting with a small value such as 0.1, but each source-domain combination still needs its own evaluation.

Conclusion

This paper did not follow the trend of pushing for a deeper ViT backbone nor did it attempt to reverse domain shift with complex adversarial learning techniques. Instead, it chose a relatively simple yet effective approach:

Re-understanding local textures and statistical features, allowing Vision Transformers to learn to perceive differences.

Each design in S-Adapter directly addresses two fundamental problems in FAS tasks:

  • Recognizing local details
  • Resilience to style differences across environments

Stable generalization is not simply a matter of stacking a more complex network. It comes from understanding and refining what the task needs. Across the tested cross-domain settings, the authors show that this choice is more than a lucky result and may prove useful beyond a single dataset.