{'fraction_non_alphanumeric': 0.03174431981593327, 'fraction_numerical': 0.009203336209375898, 'mean_word_length': 4.879729444092158, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
PatchNet: A Simple Face Anti-Spoofing Framework via Fine-Grained Patch Recognition

Face anti-spoofing (FAS) plays a critical role in securing face recognition systems from different presentation attacks. Previous works leverage auxiliary pixel-level supervision and domain generalization approaches to address unseen spoof types. However, the local characteristics of image captures, i.e., capturing devices and presenting materials, are ignored in existing works and we argue that such information is required for networks to discriminate between live and spoof images. In this work, we propose PatchNet which reformulates face anti-spoofing as a fine-grained patch-type recognition problem. To be specific, our framework recognizes the combination of capturing devices and presenting materials based on the patches cropped from non-distorted face images. This reformulation can largely improve the data variation and enforce the network to learn discriminative feature from local capture patterns. In addition, to further improve the generalization ability of the spoof feature, we propose the novel Asymmetric Margin-based Classification Loss and Self-supervised Similarity Loss to regularize the patch embedding space. Our experimental results verify our assumption and show that the model is capable of recognizing unseen spoof types robustly by only looking at local regions. Moreover, the fine-grained and patch-level reformulation of FAS outperforms the existing approaches on intra-dataset, cross-dataset, and domain generalization benchmarks. Furthermore, our PatchNet framework can enable practical applications like Few-Shot Reference-based FAS and facilitate future exploration of spoof-related intrinsic cues.


Introduction
Face anti-spoofing (FAS) is a crucial technique to prevent face recognition systems from security attacks. With the advance of deep neural network, several learning-based approaches were proposed to discriminate live faces from physical presentation attacks. Figure 1. The face recognition model learns a face embedding space to discriminate between identities. Our fine-grained patchtype recognition model learns a patch embedding space to discriminate between patches with different capture characteristics.
Previous face anti-spoofing methods are highly limited by the scale and variation of the datasets. Commonly used datasets [1,5,18,27,34] contain less than 100 identities during training, and the spoof images are captured under limited variation. Based on our observation, training on such datasets with a binary classification model is prone to overfit to the biases introduced by the data collection, and the learned features are vulnerable in the unseen testing scenarios. Therefore, previous face anti-spoofing works [14,15,18,21,29,30] leverage auxiliary pixel-wise supervision (e.g., the facial depth map and reflection map) as a strong prior knowledge to achieve better generalization ability under testing scenarios with unseen illumination or spoof types. The other FAS works [19,33] propose to adopt Generative Adversarial Network (GAN) to disentangle the feature maps of live faces and spoof images by reconstructing new live and spoof facial images. Despite the effectiveness of these spoof-detecting techniques, it is still remained as an open question to describe the intrinsic cues learned from networks. Yu et al. [29] rephrase FAS as a structural material recognition problem, which assumes that the discrimination of the structural materials between human facial skin and physical spoofing carriers is the essence for FAS tasks. Following the similar motivation, we believe that the capability of recognizing and comparing different fine-grained material types is the key to learn robust intrinsic cues for FAS.
In this paper, we propose PatchNet which learns discriminative features based on patches cropped from the entire face regions. Inspired by previous works [2,6,28], the patch-level inputs can enhance the data variation and enforce the network to learn spoof-specific features in the local region, and thus prevent the network from overfitting to the biases introduced by datasets. Instead of resizing the input face images into the same size as adopted by recent FAS works, we directly crop the fixed-size patches from raw facial captures to avoid the distortion of discriminative FAS cues. With the patch-level inputs, our PatchNet aims at classifying the corresponding fine-grained categories, i.e., the capturing devices and presenting materials, and we denote each category as a specific "patch-type". To enforce the network to learn robust spoof-related feature to recognize unseen patch types during testing, we adopt the angular margin-based softmax loss that is commonly used in face recognition tasks [8,23,25], which aims to optimize the face embedding on the normalized hypersphere ( Figure 1). Moreover, since the patch type classes are not symmetric between live and spoof faces, we propose "asymmetric angular margin loss" and impose a larger margin on live type classes. Inspired by the recent works on self-supervised learning [3,4,10], and the fact that material patterns are presented spatially in the entire face region, we also propose "self-supervised similarity loss" to regularize the features with location and rotation invariance.
To demonstrate the effectiveness of PatchNet, we conduct extensive experiments on intra-dataset, cross-dataset, and domain generalization benchmark datasets, and Patch-Net achieves the state-of-the-art performance under most testing scenarios. Moreover, we also conduct the ablation study to further investigate the proposed components.
Our contributions are summarized as follows: • We reformulate face anti-spoofing as a fine-grained patch recognition problem, and design a simple framework called PatchNet to learn an embedding space to encode intrinsic cues from local patches to represent captures' characteristics.
• We propose novel Asymmetric Margin-based Softmax Loss and Self-supervised Similarity Loss to supervise the PatchNet training. While the former helps to learn a more generalized patch type embedding space to address the asymmetry between live and spoof, the latter can enforce the patch feature to be invariant within a single capture.
• The proposed framework could achieve state-of-theart performance on intra-dataset, cross-dataset, and domain generalization benchmarks simultaneously with-out auxiliary pixel-wise supervision and domain generalization techniques. Moreover, the learned patch embedding space can enable applications like Few-Shot reference FAS and patch type retrieval, which can boost the FAS performance in certain deployment scenarios.

Related Works
Auxiliary-based Methods. Most of the recent works leverage auxiliary tasks as the prior knowledge to guide the feature learning toward more generalizable cues. Liu et al. [18] proposed to employ the depth map and rPPG as strong supervision signals for live samples to regularize the features. Kim et al. [13] further leveraged the reflection maps as the supervision signal for spoof samples. Many other FAS methods [9,14,15,20,21,29,30] also heavily rely on similar auxiliary pixel-wise supervision to improve their FAS model performance. Even though the feature learning can benefit from such supervision, the pseudo ground truths for those tasks are not accurate, and the generation of those supervision signals takes high computation resources.
Domain Generalization FAS Methods. In the face antispoofing community, domain generalization techniques are developed to address the domain shift between different anti-spoofing datasets. Shao et al. [21] employed meta-learning techniques to simulate the target domain shift during the training process to regularize the feature learning directions. Wang et al. [24] proposed to learn domain-independent features via a disentangled representation learning framework. The most related work to ours is [12], which treats live and spoof samples asymmetrically and applies adversarial loss and triplet loss to regularize the features in the normalized space. Actually, domains are hard to define in FAS tasks, as even within the same dataset, there are captures with very different capture devices. While people are using generalization methods to find common features across collections and spoof types, we aim to break the concept of domain and propose to learn a generic embedding space that encodes capture characteristics explicitly.

Overview
As illustrated in Fig. 2, we reformulate face antispoofing as a fine-grained patch-type recognition problem and propose a simple training framework to learn the patch features efficiently. First, we apply certain transform on the original image to obtain the patch inputs, and the patch features are extracted by an encoder and then normalized in the feature space. Based on the meta-info from the training dataset, we split the categories finely based on the presenting materials and capture devices. For example, in Figure 2. Overview of our proposed PatchNet framework. We address the face anti-spoofing with a fine-grained patch-type recognition model. The patch-type classes are pre-defined by the combination of the capture device and the presenting material, and the patch inputs are extracted from the face captures by non-distorted augmentation operations. Asymmetric Angular Margin Softmax Loss is employed in the last classification layer to impose larger angular margin on live classes. Self-Supervised Similarity Loss is applied to enforce the patch feature invariance within a single capture.
CASIA-FASD, there are two different spoof mediums and three different capture resolutions, so there are nine finegrained patch types (three live and six spoof types).
Inspired by the latest face recognition approaches, during training we employ angular margin-based softmax loss, which can force feature cluster for each category to be compactly distributed and enable better generalization ability. Furthermore, as the distribution discrepancies between spoof samples are larger than live samples, we treat live and spoof samples asymmetrically: force the model to learn a more compact cluster within live samples while leaving spoof samples more dispersed in the feature space. We modify the angular margin-based softmax loss and apply asymmetric margin onto live and spoof patch types: imposing larger angular margin on live types to push more compact boundaries. Finally, the self-supervised similarity loss further regularizes the patch features by applying the positive part of the contrastive loss on two transformed patch views from a single whole face image. Given that spoofspecific discriminative information is present spatially in the entire face region, the features between two different patch views from the same face capture should be similar.

Patch Features Extraction
We want to avoid any transform which can lead to image distortion or the reduction of the important spoof-related information. Given the cropped face region x i from the raw capture, the two augmented patch views from x i are T is the sequence of non-distorted augmentation operations, which only have random horizontal flip, random rotation, and fixed size cropping. The two input patches are then passed into the encoder E θ and normalization layer to get the final features:

Fine-Grained Patch Recognition
Assuming we have N patch type classes in the training dataset, which consists of k live and N − k spoof classes. Each input patch t(x i ) belongs to one fine-grained ground truth class y i ∈ {L 1 , L 2 , ...L k , S 1 , S 2 , ...S N −k }, and the Angular-Margin Softmax Loss is applied to regularize the patch features. The Angular-Margin Softmax Loss has many variants [8,16,17,23,25] and is commonly used in face recognition to improve the generalization ability to open-set identities. In this work, we employ AM-Softmax [23] loss to optimize the fine-grained patch recognition model and modify it to address the asymmetric nature in face anti-spoofing.

Preliminaries
The formulation of the original Softmax loss is given by where f is the input of the fully connected layer for classification (f i denotes the i-th sample), W j is the j-th column of the fully connected layer, and y i is the ground truth label of the i-th sample. The term W T yi f i is also called the target logit of the i-th sample.
The large-margin property is introduced by Sphereface [16], which defines a general function ψ(θ) to impose the angular margin between feature and weight vectors. After applying feature and weight normalization (∥W yi ∥ = ∥f i ∥ = 1), the loss function becomes where in AM-Softmax [23] the function ψ(θ) is defined as During implementation, the input after normalizing both the feature and the weight is actually Then it scales the cosine values using a hyper-parameter s and the final AM-Softmax loss function becomes

Asymmetric AM-Softmax Loss
We The final Asymmetric Recognition Loss on two augmented patch views from the image is formulated as

Self-Supervised Similarity Loss
Given two different patch views from the same face image, the self-supervised similarity constraint is applied to enforce the features to be similar. Therefore, the spoofrelated feature can be learned with patch location and rotation invariance.

Total Loss
The total loss L of the proposed framework during training is where α 1 and α 2 are the weights to balance the influence of loss components. In all of the experiments, we set α 1 = α 2 = 1.0.

Testing Strategy
Given a test face image, we uniformly crop patches from the whole image for the network inference, with the patch size the same as the one in the training process. Assuming we have P cropped patches features (f 1 , f 2 , ...f P ) from one face image, then the average live probability can be obtained by the sum of live class probabilities in the last fully connected layer: 4. Experiments

Datasets and Protocols
Databases. Five databases OULU-NPU [1] (denoted as O), SiW [18] (denoted as S), CASIA-FASD [34] (denoted as C), Replay-Attack [5] (denoted as I), MSU-MFSD [27] (denoted as M) are used in the testing protocols. OULU-NPU and SiW are large-scale high-resolution databases containing four and three protocols to validate the generalization (e.g., unseen environment and spoof mediums) of models, respectively, which are utilized for intra-dataset testing. CASIA-MFSD, Replay-Attack, and MSU-MFSD are databases that contain low-resolution videos with much fewer video clips and are used for cross-dataset testing to validate the generalization ability to testing data with large distribution shift. There are three capture devices with quality ranging from low to high in CASIA-FASD, two devices in SiW and MSU-MFSD, and only one device in the other datasets. The fine-grained class number and the other statistics of databases are shown in Tab. 1. Note that in Oulu-NPU, even the collections are captured by six different types of phones, the quality and fine details are pretty similar, so we only split the patch type into five classes in total. More details and sample images can be found in the supplementary material.
(ACER) for a fair comparison. Half Total Error Rate (HTER) and Area Under Curve (AUC) are adopted in the cross-dataset testing between OULU-NPU, CASIA-MFSD, Replay-Attack, and MSU-MFSD.

Implementation Details
All face anti-spoofing datasets above are stored in video format originally. We randomly select three frames from each video clip and use the state-of-the-art face detector RetinaFace [7] to crop the face for training. We set the fixed patch crop size as 160, and set the hyperparameter s = 30.0, m l = 0.4, m s = 0.1 in all protocols. We use ResNet18 [11] as the patch feature encoder, and we did not see much performance difference while using an encoder with larger capacity (as shown in the supplementary materials). Models are trained with SGD optimizer and the initial learning rate is 0.002. We train models with maximum 200 epochs while the learning rate halves every 90 epochs. During testing, we uniformly crop the fixed-size patches from the face input image: the minimum x and y coordinates are size/2.0, and the maximum x and y coordinates are width − (size/2.0) and height − (size/2.0), respectively. In all of the experiments during testing, we uniformly sample 3 patch anchors on each side, which results in P = 9 patches for score averaging.

Intra-Dataset Testing
We conduct experiments on Oulu-NPU [1] and SiW [18] for intra-dataset testing results. We compare the results with the most recent face anti-spoofing methods in the following.

Results on Oulu-NPU
Oulu-NPU [1] has four challenging protocols, which evaluate the model robustness against the unseen environment, unseen spoof mediums, unseen capture devices, and all of the above, respectively. The number of classes during training are 5, 3, 5, and 3, respectively. As shown in Tab. 2, our simple patch-based recognition approach achieves the best performance in all protocols. It clearly verifies the better generalization ability of the features learned through the patch recognition proxy tasks.

Ablation Study
In this subsection, all ablation studies are conducted on Protocol 1 (different illumination conditions and location between the train and test sets) of OULU-NPU [1] to explore the details of our patch-based recognition framework.    Table 5. Ablation study of margin choices in LAsym.
Impact of Each Component. Tab. 4 shows the ablation study of each component in our proposed framework. The first row is the naive baseline (ACER: 6.25%) which formulates the face anti-spoofing as a binary classification problem (trained with the standard Cross Entropy loss) with the resized 256x256 face input. Surprisingly, by only adopting the fine-grained classes and raw frame cropping strategies, we can improve the performance significantly to 1.88% ACER. It shows that the naive baseline model could overfit to the high-level biases in the public FAS dataset, which only contains limited background and identities. Moreover, the fine details in cropped patches from raw frames are very critical to discriminate between different patch types in high-quality datasets like OULU-NPU. From the lower part of the table, we can observe the advantage of the proposed margin-based classification loss and the self-supervised similarity loss. It is clear that both regularization techniques can facilitate the encoder to learn more intrinsic features related to the capture device's characteristics and presenting materials.
Impact of Patch Crop Size. Fig. 3 demonstrates the ACER(%) on OULU-NPU protocol 1 between different crop sizes. We can observe that larger patch sizes during training might be prone to overfit to biases from the face capture. With the regularization of patch recognition loss and patch-based augmentation to increase training data variance, the overall performance does not differ much when enlarging the patch size. However, when the patch size is too small (e.g., 64), the performance degrades significantly as the capture characteristics can not be learned with very limited information.
Asymmetric Margin Choices. We conduct ablation experiments to verify the effectiveness of our asymmetric margin design in the angular margin softmax loss. From Tab. 5, we can observe that adding angular margins can signifi-  Table 6. The results of cross-dataset testing between CASIA-MFSD and Replay-Attack. The evaluation metric is HTER(%).
cantly improve the generalization capability and outperform the model without any margin. Furthermore, adding a very large margin to spoof patch types which have more diverse appearances would hurt the discrimination power of learned features. We find that PatchNet works well on all testing protocols with the margin choice m l = 0.4, m s = 0.1.

Experiments between C and I
First, following the related works, CASIA-MFSD (C) [34] and ReplayAttack (I) [5] are used for cross-dataset experiments, and the results are measured in HTER. During training, the numbers of fine-grained patch-type classes are 9 and 4 in C → I and I → C protocols, respectively. The results are shown in Tab. 6. Given the limited number of clips and low-quality videos from the ReplayAttack dataset, it is hard to learn generalizable features which can perform very well on other datasets, so the error rate in protocol I → C is still high compared with C → I. Our proposed framework can achieve competitive performance compared to previous works in both protocols.

Domain Generalization Experiments
Some recent FAS works [12,21,24] consider each dataset as one domain and promote the domain generalization benchmark in FAS, which utilizes three datasets for training, and the remaining one as testing. As we aim to distinguish the patch type in the fine-grained manner, our proposed framework can be directly used to evaluate such benchmark without employing further generalization techniques (e.g., adversarial training or meta-learning). With access to more different patch types with more diverse capture devices, our framework is capable of learning more discriminative features through the patch recognition proxy task. to learn robust local features to address both high and low resolution scenarios. We also conduct an ablation study in this benchmark to explore the influence of each component in our framework and show the results in Tab. 7. In the first ablation experiment, we split the patch classes using the strategy proposed by SSDG [12]: It aggregates the live samples as one class and treats spoof samples from each other dataset as one class, which results in 4 classes. The results verify that the proposed fine-grained class split, L Asym , and L Sim are all important to regularize the network to generalize better in challenging FAS tasks.

Visualizations
Patch Feature Distribution. In Fig. 4, we visualize the patch features by t-SNE [22] from OULU-NPU protocol 1, which both the training and testing sets consist of 5 patch types (live, print1, print2, screen1, screen2). We can observe in (b) that the model trained without margin cannot distinguish print1 and print2 types very well. The distribution for the live samples is more compact, and clusters are separated better for the model trained with the margin. The training and testing feature sets are aligned well in the feature space.
In Fig. 5, we visualize the feature distribution in the protocol M&I&O to C. We can observe that the features from the training set are separated well in the fine-grained manner. As dataset C contains three different quality capture devices, the corresponding three live classes are located separately in the embedding space. Aligning with the device characteristics, we observe that features from C3 L are close to O L, which both types are captured from high-quality capture devices. Moreover, low-quality devices like C1 L exhibit similar appearance with that from similar quality device M1 L. It implies that the patch embedding space encodes the capture characteristic well.  Patch Score Map. In Fig. 6, we compute the scores from patches across the whole image and visualize the live probability in the overlapped heat map. The samples are from the testing set of OULU-NPU protocol 1. The patch scores across the whole face input image are primarily consistent, except for some background and boundary parts, which is expected as the spoof cues should be learned from the face

Applications
Testing on each Capture Device. Following the observation in Sec. 4.6, we argue that instead of testing on the whole dataset, it is more feasible to test the antispoofing performance on each device separately (e.g., in the CASIA-FASD dataset). We re-organize the testing dataset in O&C&I to M and O&M&I to C protocols, which is splitting the testing data by their capture device ID into 2 (M1, M2) and 3 (C1, C2, C3) groups, respectively. The crossdataset anti-spoofing performance on the new split dataset of these two protocols is shown in Tab. 9. We observe that anti-spoofing performance on both devices in the M dataset are better than the average performance using the whole dataset, which is reasonable as the testing sets are smaller. However, only one device (the high-quality one C3) in the C dataset is better than the average performance, which aligns with the t-SNE visualization in Fig. 5. The capture images of C2 have many noises and image compression effects, which can lead to significant degradation of the discriminative power of features. With the detailed performance report on each device, we can further improve the anti-spoofing system or improve the quality of the problematic capture devices as well.
Few-Shot Reference Anti-Spoofing. With the learned patch embedding space which encodes intrinsic patch features to discriminate between patch types, the distance between features in the embedding space can be used to measure the similarity between patch types. As the features are already normalized in the space, we can compute the cosine distance between features to enable a new application: fewshot reference anti-spoofing. While there is a new capture device, it is easier to acquire some live face image samples, and those sample features can be used as the reference in the embedding space. We compute the distances between other testing features and live reference to obtain the similarity scores. Higher similarity scores mean the samples are more likely to be live. The 5-shot and 10-shot live reference antispoofing performance are reported in Tab. 9. We can conclude that with the live reference features and the learned  Table 9. Split testing and few-shot live reference testing on each capture device. The few-shot testing score is averaged by 10 experiment runs. AUC(%) score is reported. patch embedding space, the performance can be boosted a lot in practical scenarios. Patch Type Retrieval. The normalized patch embedding space can be used for the patch type retrieval application, and can boost the FAS performance on certain capture devices. For example, after training the feature space with M&C&I datasets to recognize 21 patch types, we can measure the similarity between testing patch types and training patch types. As shown in Fig. 7, we take a live sample from O dataset as the query, and retrieve the training patch types by computing the cosine distance with each type weight vector. The top-7 retrieval patch types are (M2 L, C3 L, M1 L, M1 S2, C2 L, M2 S2, I L). Some spoof types from M dataset have higher ranking than live types from C2 and I datasets, which have low quality captures. To optimize the performance while testing on O dataset, we can 1) remove ambiguous live types (C2 L, C1 L, I L) during testing, or 2) re-define the class for (C2 L, C1 L, I L) as "spoof" for training. Both strategies can boost the performance to 95.27% and 95.87% AUC, respectively.

Conclusions and Future Work
In this paper, we reformulate face anti-spoofing as a finegrained patch type recognition task and present a simple training framework called PatchNet to efficiently learn the patch embedding space which encodes the spoof-related capture characteristics. The novel loss functions are designed to enhance the feature discrimination power. Extensive experiments on challenging FAS protocols verify the effectiveness of the proposed method. We note that exploration of a generic embedding space to discriminate different captures is still at an early stage. Future directions include: 1) Learning a more generalized embedding space by datasets with more variations or transferred from the material perception task, and 2) Investigation into the Few-Shot FAS protocols which have more practical values.