All posts

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.

Abstract drawing of two four-stage encoders side by side, purple for appearance and green for motion, joined at every stage by a crossing link with a small gate, and the four links running down into one output point.
Two encoders, four meeting points, one score.

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:

X∈ℝ16×3×224×224x~c=xc−μcσcμ=(0.485, 0.456, 0.406),σ=(0.229, 0.224, 0.225)

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 X that ask and a set Y that are asked, three learned matrices produce queries, keys, and values:

Q=XWQ,K=YWK,U=YWU

We write the values as U because V will stand for the video stream later. When X and Y are the same set, this is self-attention; when they differ, it's cross-attention. The output is

Attention(Q,K,U)=softmax(QK⊤dh)U

or, for one token at a time,

αmn=exp(qm·kn/dh)∑n′exp(qm·kn′/dh)om=∑nαmnun

Every row of weights αm· is non-negative and sums to one, so each output om 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 dh has a reason. If the entries of a query and a key are independent, with mean 0 and variance 1, then

Var(q·k)=∑j=1dhVar(qjkj)=∑j=1dh𝔼[qj2]𝔼[kj2]=dh

so the raw scores grow with the head dimension. With dh=32, 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 dh 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:

MHA(X,Y)=[head1;…;headh]WOheadj=Attention(XWjQ, YWjK, YWjU)

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 M×M=7×7 tokens. For an h×w grid with C features, the two costs are

Ω(MSA)=4hwC2+2(hw)2CΩ(W-MSA)=4hwC2+2M2hwC

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

2(hw)2C2M2hwC=hwM2=56272=64

Windows that never overlap would never share information, so every second block shifts the window grid by ⌊M/2⌋=3 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:

softmax(QK⊤dh+B)UBmn=B^[Δymn, Δxmn]B^∈ℝ(2M−1)×(2M−1)

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:

z^l=W-MSA(LN(zl−1))+zl−1zl=MLP(LN(z^l))+z^lz^l+1=SW-MSA(LN(zl))+zlzl+1=MLP(LN(z^l+1))+z^l+1

Between stages, each 2 × 2 group of neighboring tokens is concatenated and projected, which halves the grid and doubles the features:

xa,b′=W[x2a,2b; x2a+1,2b; x2a,2b+1; x2a+1,2b+1]W∈ℝ2C×4C

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

162×2244×2244=8×56×56 tokensP·M2=8·72=392 tokens per window

Its windows are blocks of P×M×M=8×7×7 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 (2P−1)(2M−1)2 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 i, the two encoders produce feature maps with the same spatial size and the same number of features but a different number of time steps:

Si∈ℝ16×Hi×Wi×CiVi∈ℝ8×Hi×Wi×Ci(Hi,Ci)∈{(56,128), (28,256), (14,512), (7,1024)}

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 k at stage i,

S~i,t,k=ai,k,0Si,2t,k+ai,k,1Si,2t+1,k+bi,kt=0,1,…,7

Depthwise means that every channel has its own two weights and its own bias, so the adapter adds only 3Ci parameters per stage. A plain average is the special case

ai,k,0=ai,k,1=12,bi,k=0⟹S~i,t,k=12(Si,2t,k+Si,2t+1,k)

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 di, then cut into non-overlapping 7 × 7 windows at each of the 8 aligned positions:

Ai=Win7(LN(S~i)WiS)Bi=Win7(LN(Vi)WiV)WiS,WiV∈ℝCi×di

A window holds 49 tokens. With hi heads of 32 dimensions each, di=32hi, and the number of windows in one clip is Ni=8·(Hi/7)·(Wi/7):

StageGridEncoder features CiFusion width diHeads hiWindows Ni
156 × 56128642512
228 × 282561284128
314 × 14512256832
47 × 71,02425688

Cross-attention in both directions

Inside each window pair (Ai,Bi), each stream attends to the other:

Aia=Ai+γiS𝒞iS←V(Ai,Bi)Bia=Bi+γiV𝒞iV←S(Bi,Ai)

Here 𝒞S←V is multi-head attention with queries from the spatial window and keys and values from the video window, and 𝒞V←S is a separately parameterized module that does the reverse:

𝒞S←V(A,B)=[head1;…;headh]WOheadj=softmax((AWjQ)(BWjK)⊤32)BWjU

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

2·h1·N1·492=2·2·512·2401≈4.9×106

entries. Attention between all 3,136 tokens at each of the 8 positions would need

2·h1·8·31362≈3.1×108

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:

Aif=Aia+γiF,SFFN(LN(Aia))FFN(x)=W2GELU(W1x+b1)+b2GELU(x)=xΦ(x)

Here W1 maps di features to 4di and W2 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 γiF,V. With all four gates of a module at zero, the module starts as the identity: Aif=Ai and Bif=Bi. The gradients show what happens next. Writing 𝒞 for the attention output and θ𝒞 for its parameters,

∂ℒ∂γ=⟨∂ℒ∂Aa, 𝒞(A,B)⟩F∂ℒ∂θ𝒞=γ(∂𝒞∂θ𝒞)⊤∂ℒ∂Aa=0at γ=0

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 S^i and V^i, the module builds

Ei=LN4di[S^i; V^i; |S^i−V^i|; S^i⊙V^i]ri=Wir[meant,h,wEi; maxt,h,wEi]+bir∈ℝ256

The four parts are joined along the feature axis, so Ei has 4di features at each of the 8×Hi×Wi positions. Mean and max pooling over all positions give 8di numbers, and a linear layer maps them to 256.

PartFeaturesWhat it holds
S^idiThe appearance stream after the exchange
V^idiThe motion stream after the exchange
|S^i−V^i|diHow far apart the two are, feature by feature
S^i⊙V^idiWhere 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 s and v the two feature vectors,

∑c(s⊙v)c=⟨s,v⟩‖s−v‖22=‖s‖22+‖v‖22−2⟨s,v⟩‖s−v‖1=∑c|sc−vc|

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 N values,

mβ(x)=1βlog(1N∑n=1Neβxn)limβ→0mβ(x)=1N∑n=1Nxnlimβ→∞mβ(x)=maxnxn

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,

Si+1=Stagei+1Swin(Si)Vi+1=Stagei+1Video(Vi)

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 z:

r=[r1;r2;r3;r4]∈ℝ1024h=Drop0.3(GELU(WhLN(r)+bh))∈ℝ512z=w⊤h+b

The logit becomes a probability through the sigmoid, and training minimizes binary cross-entropy:

p=σ(z)=11+e−zℒ=−[ylogp+(1−y)log(1−p)]∂ℒ∂z=p−y

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:

z¯=17∑c=17zcp=σ(z¯T)y^=1[p≥q*]

The temperature T and the threshold q* are fitted on validation data. Because the sigmoid is increasing, dividing by T changes how confident the probabilities look but never changes which of two videos scores higher.

The whole network in one line

Writing Σi and Ψi for stage i of Swin-B and Video Swin-B, 𝒜i for the temporal adapter, Ri for the TLBG-HCA module with its readout, ⊕ for concatenation, and g for the classifier, the logit of one clip is

z(X)=g(⨁i=14Ri(𝒜i(Σi(X)), Ψi(X)))

and the parameters add up as follows:

86.7 M⏟Swin-B+87.6 M⏟Video Swin-B+6.5 M⏟fusion and classifier=180.9 M

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.”

Written by

Eugene T. Custodio

Lead AI Researcher, SwinFusion++

Eugene leads the AI research for SwinFusion++: Face-Aligned Spatio-Temporal Swin Transformer for Deepfake Detection, the thesis behind OriginAI. His research focuses on computer vision and large language models.

Earlier research he led

  • Evaluating Gradient Boosting for Phishing Detection: A Focus on URL Features
  • YOLOv8n-Based Person Detection for Campus Attendance Support: A Site-Specific Study at the University of the East, Manila
  • TaG-DT YOLO11-M: Taxonomy-Guided Dual-Task Learning for Waste Detection and Classification
Meet the whole team

Not Sure About A Video?

Scan it now. It's free, there's no sign-up, and your video is deleted right after.