How SwinFusion++ Works: The Architecture, Step by Step
SwinFusion++ reads a face video with two transformers at once, one that studies each frame and one that studies short moments of motion, and lets them compare notes at four levels of detail. This post walks through the math behind every part, with a plain-language version after each step.
A deepfake can give itself away in two places. Inside a single frame, the skin of a swapped face may be slightly too smooth, or its edge may not blend into the neck. Across frames, the mouth may not quite follow the speech, or the face may shimmer as the head turns. SwinFusion++ is built to look in both places at once.
It runs two pretrained transformers side by side on the same clip. Swin-B reads every frame on its own, and Video Swin-B reads short spans of two frames together. At four points along the way, a module we call TLBG-HCA lets the two compare what they have found. This post goes through every part in order, with the math, and each technical section ends with a short version in plain words. It covers only how the network is built; how we trained and evaluated it is in our paper.
The input: one face, sixteen times
SwinFusion++ never sees a whole video at once. We sample 64 timestamps spread evenly across the video, detect the face in each with MTCNN, follow the same person from one frame to the next with FaceNet embeddings, and align every face with a five-point similarity transform so that the eyes, nose, and mouth land on the same pixels in every crop. A clip is 16 of these crops. Each one has three color channels and is 224 pixels square, and each channel is scaled to [0, 1] and standardized with the ImageNet mean and standard deviation:
A video gives 48 tracked faces, and seven clips are cut from them, starting at positions 0, 5, 11, 16, 21, 27, and 32, so neighbouring clips overlap. The network scores each clip separately; how the seven scores become one answer comes at the end of this post.
Attention, the operation everything is built on
Both encoders and the fusion module are built from one operation, scaled dot-product attention (Vaswani et al., 2017). It works on tokens. Here, a token is a vector of numbers that describes one small patch of a face. Given a set of tokens that ask and a set that are asked, three learned matrices produce queries, keys, and values:
We write the values as because will stand for the video stream later. When and are the same set, this is self-attention; when they differ, it's cross-attention. The output is
or, for one token at a time,
Every row of weights is non-negative and sums to one, so each output is a weighted average of the value vectors and always lies inside their convex hull. Attention mixes the information it's given; it can't produce values outside that range.
The division by has a reason. If the entries of a query and a key are independent, with mean 0 and variance 1, then
so the raw scores grow with the head dimension. With , their standard deviation would be about 5.7, enough to push the softmax toward putting almost all of its weight on one token, where its gradients nearly vanish. Dividing by brings the variance back to 1. In practice, attention runs as several heads in parallel, each with its own matrices, and their outputs are joined and mixed by one more matrix:
Swin-B: one frame at a time
Swin-B (Liu et al., 2021) cuts a 224 × 224 frame into 4 × 4 pixel patches and maps each patch's 48 values (4 × 4 × 3) to 128 features, which gives a 56 × 56 grid of tokens. Attending over all 3,136 tokens at once would be expensive, because the attention term grows with the square of the number of tokens. Swin restricts attention to non-overlapping windows of tokens. For an grid with features, the two costs are
The first term covers the linear projections and is the same for both; the second is the attention itself. At the first stage, the ratio between the two attention terms is
Windows that never overlap would never share information, so every second block shifts the window grid by tokens in each direction. A patch near the edge of a window then lands in a window with its former neighbors. Inside a window, attention also adds a learned bias that depends only on the relative offset between two tokens, read from a small table:
Blocks come in pairs, one with regular windows and one with shifted windows, each followed by a two-layer MLP, with layer normalization before every step and a residual connection around it:
Between stages, each 2 × 2 group of neighboring tokens is concatenated and projected, which halves the grid and doubles the features:
Swin-B has four stages with 2, 2, 18, and 2 blocks, and its feature maps shrink from 56 × 56 with 128 features to 28 × 28 with 256, 14 × 14 with 512, and 7 × 7 with 1,024. In SwinFusion++, Swin-B starts from ImageNet weights and runs on each of the 16 frames separately.
Video Swin-B: short moments instead of single frames
Video Swin-B (Liu et al., 2022) applies the same design in three dimensions. Its patches are tubelets: a 4 × 4 patch followed through 2 consecutive frames. A 16-frame clip therefore becomes
Its windows are blocks of tokens that cover all eight tubelet positions, and they shift in time as well as in space. The relative position bias table becomes three-dimensional, with entries. Patch merging works only on the spatial grid, so the time axis stays at 8 positions through all four stages, while the spatial sizes and feature counts match Swin-B exactly: 56, 28, 14, and 7, with 128, 256, 512, and 1,024 features. Video Swin-B starts from weights trained on the Kinetics-400 action dataset.
Two streams, two clocks
At every stage , the two encoders produce feature maps with the same spatial size and the same number of features but a different number of time steps:
Swin-B has 16 time positions because it read 16 frames; Video Swin-B has 8 because each tubelet spans two frames. To compare them position by position, SwinFusion++ first aligns the Swin-B stream with a learned depthwise convolution whose kernel and stride are (2, 1, 1) in (time, height, width). For channel at stage ,
Depthwise means that every channel has its own two weights and its own bias, so the adapter adds only parameters per stage. A plain average is the special case
and training is free to move away from it, for example by weighting one frame of each pair more heavily in some channels. Attention itself doesn't need equal lengths: 16 queries could attend to 8 keys. The adapter is there to state which positions are meant to correspond. Shared coordinates give the two streams a common reference, though they don't guarantee that the two encoders mean the same thing by the same feature.
TLBG-HCA: where the two streams meet
The fusion module's name lists what it does: tubelet-aligned (it works on the aligned positions above), local (it attends within small windows), bidirectional (each stream reads the other), gated (each exchange passes through a learned scale), hierarchical (one module per stage, four in all) cross-attention. The diagram below shows one module.
Projecting and cutting into windows
Each stream is normalized and projected to a smaller width , then cut into non-overlapping 7 × 7 windows at each of the 8 aligned positions:
A window holds 49 tokens. With heads of 32 dimensions each, , and the number of windows in one clip is :
| Stage | Grid | Encoder features | Fusion width | Heads | Windows |
|---|---|---|---|---|---|
| 1 | 56 × 56 | 128 | 64 | 2 | 512 |
| 2 | 28 × 28 | 256 | 128 | 4 | 128 |
| 3 | 14 × 14 | 512 | 256 | 8 | 32 |
| 4 | 7 × 7 | 1,024 | 256 | 8 | 8 |
Cross-attention in both directions
Inside each window pair , each stream attends to the other:
Here is multi-head attention with queries from the spatial window and keys and values from the video window, and is a separately parameterized module that does the reverse:
For every head and every window, the attention matrix is 49 × 49: each of the 49 spatial tokens gets a probability distribution over the 49 video tokens at the same place and time. Both directions read the original normalized windows in parallel, so neither direction sees the other's output. The windows aren't shifted and never span two tubelet positions, so temporal context reaches the module only through Video Swin-B and the adapter. Staying local also keeps the cost small. At stage 1, the attention maps of one module hold
entries. Attention between all 3,136 tokens at each of the 8 positions would need
which is 64 times as many, the same factor as in Swin-B.
Gates that start at zero
Each exchange above is scaled by a gate : a single learned number per direction and stage, initialized to 0 and used as is, with no sigmoid or tanh. The idea comes from ReZero (Bachlechner et al., 2021). Each attention step is followed by its own gated feed-forward step:
Here maps features to and maps them back, is the cumulative distribution function of the standard normal distribution, and dropout of 0.10 is applied to the attention and feed-forward outputs. The video side mirrors this with its own gate . With all four gates of a module at zero, the module starts as the identity: and . The gradients show what happens next. Writing for the attention output and for its parameters,
On the first update, only the gate can move. Once it leaves zero, gradient starts reaching the attention weights behind it, in proportion to the gate. After training, the gates are fixed numbers: they don't depend on the input, and they aren't a measure of how much the model trusts either stream.
The readout: four views of every position
After the windows are put back together into full grids and , the module builds
The four parts are joined along the feature axis, so has features at each of the positions. Mean and max pooling over all positions give numbers, and a linear layer maps them to 256.
| Part | Features | What it holds |
|---|---|---|
| The appearance stream after the exchange | ||
| The motion stream after the exchange | ||
| How far apart the two are, feature by feature | ||
| Where both respond strongly together, with the same sign |
The difference and product terms are the per-feature pieces of familiar comparisons. For one position, with and the two feature vectors,
so the classifier receives the ingredients of a dot product and of two distances, one feature at a time, and learns how much each one matters. Mean and max pooling are the two ends of one family. For values,
The mean describes the clip as a whole. The max keeps the strongest response, even if it came from a single position at a single moment.
Fusion that only reads
The enhanced grids go only to the readout. Each encoder passes its own features to its next stage,
so the fusion modules never change either backbone's forward computation. During training, gradients from the readouts still reach any encoder layers that aren't frozen.
From four readouts to one answer
The four 256-number readouts are joined and passed through a small classifier: layer normalization, a 512-unit layer with GELU, dropout of 0.30, and a single output, the logit :
The logit becomes a probability through the sigmoid, and training minimizes binary cross-entropy:
The last expression is why this pairing is convenient: the error signal that starts backpropagation is simply the gap between the predicted probability and the label. A video's seven clips are scored separately, and their logits are averaged before the probability is computed:
The temperature and the threshold are fitted on validation data. Because the sigmoid is increasing, dividing by changes how confident the probabilities look but never changes which of two videos scores higher.
The whole network in one line
Writing and for stage of Swin-B and Video Swin-B, for the temporal adapter, for the TLBG-HCA module with its readout, for concatenation, and for the classifier, the logit of one clip is
and the parameters add up as follows:
References: Vaswani et al. (2017), “Attention Is All You Need.” Liu et al. (2021), “Swin Transformer: Hierarchical Vision Transformer Using Shifted Windows.” Liu et al. (2022), “Video Swin Transformer.” Bachlechner et al. (2021), “ReZero Is All You Need.” Custodio, Degamo, Escueta, San Diego, and Sarmiento, “SwinFusion++: A Controlled Evaluation of Aligned Cross-Attention, Transfer, and Cost in Dual-Swin Deepfake Detection.”