huahua123313 commited on
Commit
b58079c
·
verified ·
1 Parent(s): 0bda4e7

Add files using upload-large-folder tool

Browse files
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ .DS_Store
2
+ __pycache__
3
+ .vscode/
GUIDE.md ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FT_work 数据集预处理完整指南
2
+
3
+ ## 📋 目录
4
+
5
+ 1. [参数详解](#参数详解)
6
+ 2. [数据集结构对比](#数据集结构对比)
7
+ 3. [使用流程](#使用流程)
8
+ 4. [文件说明](#文件说明)
9
+ 5. [示例与计算](#示例与计算)
10
+ 6. [常见问题](#常见问题)
11
+
12
+ ---
13
+
14
+ ## 参数详解
15
+
16
+ ### 1. N_EXTRACT = 10
17
+ **含义**: 从**每个视频**中提取的窗口数量
18
+
19
+ **详细解释**:
20
+ - 代码会在视频帧范围内均匀选择 10 个起始点
21
+ - 每个起始点对应一个时间窗口
22
+ - 例如:视频有 300 帧,会选择 10 个起始位置(如:0, 33, 66, 99, 132, 165, 198, 231, 264, 297)
23
+
24
+ **影响**:
25
+ - 值越大 → 每个视频生成的样本越多 → 数据集越大
26
+ - 值越小 → 每个视频生成的样本越少 → 可能丢失信息
27
+
28
+ ### 2. WINDOW_LEN = 5
29
+ **含义**: 每个窗口包含的**连续帧数**
30
+
31
+ **详细解释**:
32
+ - 从每个起始点开始,连续提取 5 帧图像
33
+ - 这 5 帧会水平拼接成一张图(宽 2500px = 5 × 500px)
34
+ - 例如:起始帧为 0,则提取帧 [0, 1, 2, 3, 4]
35
+
36
+ **影响**:
37
+ - 值越大 → 每个样本包含更多时间信息 → 但单张图片更宽
38
+ - 值越小 → 每个样本时间跨度短 → 可能捕捉不到完整动作
39
+
40
+ ### 3. MAX_SAMPLE = 100 (建议改为 0)
41
+ **含义**: 限制的**最大视频处理数量**
42
+
43
+ **⚠️ 注意**: 原代码中这个参数有 bug,建议使用改进版脚本(`preprocess_improved.py`)
44
+ - `MAX_SAMPLE = 0`: 处理所有视频(无限制)
45
+ - `MAX_SAMPLE = 100`: 只处理前 100 个视频
46
+
47
+ **建议**: 设置为 0(无限制)或根据实际情况调整
48
+
49
+ ---
50
+
51
+ ## 数据集结构对比
52
+
53
+ ### FT_work 原始结构
54
+ ```
55
+ /apdcephfs_gy5/share_303628665/joyewu/dataset/FT_work/videos/
56
+ ├── train/
57
+ │ ├── real/Real/*.mp4
58
+ │ └── fake/{AniPortrait,Joyvasa,Ditto,Hallo,Sonic}/*.mp4
59
+ ├── test/
60
+ │ ├── real/Real/*.mp4
61
+ │ └── fake/{SadTalk,EDTalk,Float}/*.mp4
62
+ └── val/
63
+ ├── real/Real/*.mp4
64
+ └── fake/{AniPortrait,Joyvasa,Ditto,Hallo,Sonic}/*.mp4
65
+ ```
66
+
67
+ **特点**:
68
+ - 按 train/test/val 分割
69
+ - fake 视频按方法分类在不同子文件夹
70
+ - **没有单独的音频文件**(需要从视频中提取)
71
+
72
+ ### AVLips 目标结构(preprocess.py 需要)
73
+ ```
74
+ AVLips/
75
+ ├── 0_real/*.mp4 # 所有真实视频
76
+ ├── 1_fake/*.mp4 # 所有假视频
77
+ └── wav/
78
+ ├── 0_real/*.wav # 真实视频的音频
79
+ └── 1_fake/*.wav # 假视频的音频
80
+ ```
81
+
82
+ **特点**:
83
+ - 不区分 train/test/val(所有数据合并)
84
+ - 真实和假视频分开存放
85
+ - **需要单独的 WAV 音频文件**
86
+
87
+ ---
88
+
89
+ ## 使用流程
90
+
91
+ ### 快速开始(推荐)
92
+
93
+ ```bash
94
+ cd /apdcephfs_gy4/share_303628665/joywu/research/LipFD
95
+
96
+ # 方式 1: 使用自动化脚本(需要手动添加执行权限)
97
+ chmod +x run_preprocess.sh
98
+ ./run_preprocess.sh
99
+
100
+ # 方式 2: 手动执行步骤
101
+ ```
102
+
103
+ ### 手动执行步骤
104
+
105
+ #### 步骤 1: 转换数据集格式
106
+
107
+ ```bash
108
+ python convert_ft_work.py
109
+ ```
110
+
111
+ **功能**:
112
+ - 将 FT_work 的所有视频(train/test/val)合并
113
+ - 分为 `0_real/` 和 `1_fake/` 两类
114
+ - 从视频中提取音频保存为 WAV 格式
115
+ - 输出到 `./AVLips/` 目录
116
+
117
+ **输出**:
118
+ ```
119
+ AVLips/
120
+ ├── 0_real/ (真实视频)
121
+ ├── 1_fake/ (假视频)
122
+ └── wav/
123
+ ├── 0_real/ (真实音频)
124
+ └── 1_fake/ (假音频)
125
+ ```
126
+
127
+ #### 步骤 2: 修改参数(可选)
128
+
129
+ 编辑 `preprocess_improved.py`:
130
+
131
+ ```python
132
+ ############ Custom parameter ##############
133
+ N_EXTRACT = 10 # 每个视频提取10个窗口
134
+ WINDOW_LEN = 5 # 每个窗口5帧
135
+ MAX_SAMPLE = 0 # 0 = 处理所有视频
136
+ ############################################
137
+
138
+ audio_root = "./AVLips/wav"
139
+ video_root = "./AVLips"
140
+ output_root = "./datasets/AVLips"
141
+ ```
142
+
143
+ #### 步骤 3: 运行预处理
144
+
145
+ ```bash
146
+ # 使用改进版(推荐)
147
+ python preprocess_improved.py
148
+
149
+ # 或使用原版
150
+ python preprocess.py
151
+ ```
152
+
153
+ **功能**:
154
+ - 从每个视频中提取帧
155
+ - 生成音频的梅尔频谱图
156
+ - 将帧和频谱图拼接成最终图片
157
+ - 输出到 `./datasets/AVLips/` 目录
158
+
159
+ ---
160
+
161
+ ## 文件说明
162
+
163
+ ### 1. `convert_ft_work.py`
164
+ **功能**: 数据集格式转换
165
+
166
+ **输入**: `/apdcephfs_gy5/share_303628665/joyewu/dataset/FT_work/videos/`
167
+
168
+ **输出**: `./AVLips/`
169
+
170
+ **依赖**:
171
+ - `ffmpeg` (用于从视频提取音频)
172
+ - `shutil`, `os`, `tqdm`
173
+
174
+ ### 2. `preprocess_improved.py` (推荐)
175
+ **功能**: 预处理脚本(改进版)
176
+
177
+ **改进点**:
178
+ - ✅ 修复 `dtype=np.uint8` 导致的索引错误
179
+ - ✅ 添加详细的错误处理
180
+ - ✅ 添加进度显示
181
+ - ✅ 检查视频长度是否足够
182
+ - ✅ 检查音频文件是否存在
183
+ - ✅ 清理临时文件
184
+
185
+ **输入**: `./AVLips/`
186
+
187
+ **输出**: `./datasets/AVLips/`
188
+
189
+ ### 3. `preprocess.py` (原版)
190
+ **功能**: 原始预处理脚本
191
+
192
+ **⚠️ 已知问题**:
193
+ - `dtype=np.uint8` 可能导致索引错误(视频帧数 > 255 时)
194
+ - 错误处理不完善
195
+ - 日志输��不够详细
196
+
197
+ ### 4. `run_preprocess.sh`
198
+ **功能**: 自动化执行脚本
199
+
200
+ **使用**:
201
+ ```bash
202
+ chmod +x run_preprocess.sh
203
+ ./run_preprocess.sh
204
+ ```
205
+
206
+ ---
207
+
208
+ ## 示例与计算
209
+
210
+ ### 示例 1: 单个视频的处理
211
+
212
+ **输入**: `video_001.mp4` (300 帧,10秒 @ 30fps)
213
+
214
+ **参数**: `N_EXTRACT=10`, `WINDOW_LEN=5`
215
+
216
+ **处理流程**:
217
+
218
+ 1. **选择起始点** (10个):
219
+ ```
220
+ [0, 33, 66, 99, 132, 165, 198, 231, 264, 297]
221
+ ```
222
+
223
+ 2. **提取窗口** (每个窗口5帧):
224
+ ```
225
+ 窗口 0: 帧 [0, 1, 2, 3, 4]
226
+ 窗口 1: 帧 [33, 34, 35, 36, 37]
227
+ ...
228
+ 窗口 9: 帧 [297, 298, 299, 300, 301] ← 会报错!(超出范围)
229
+ ```
230
+
231
+ 3. **生成输出** (10张图片):
232
+ ```
233
+ video_001_0.png (频谱图 + 5帧图像)
234
+ video_001_1.png
235
+ ...
236
+ video_001_9.png
237
+ ```
238
+
239
+ **每张图片的格式**:
240
+ ```
241
+ +------------------------+
242
+ | 音频频谱图 (500x2500) | ← 对应这5帧的时间段
243
+ +------------------------+
244
+ | 帧0 | 帧1 | ... | ← 5帧水平拼接 (500x2500)
245
+ +------------------------+
246
+ ```
247
+
248
+ ### 示例 2: 计算总输出数量
249
+
250
+ **假设**:
251
+ - 真实视频: 500 个
252
+ - 假视频: 500 个
253
+ - `N_EXTRACT = 10`
254
+
255
+ **计算**:
256
+ ```
257
+ 总视频数 = 500 + 500 = 1000 个
258
+ 总输出图片数 = 1000 × 10 = 10,000 张
259
+ ```
260
+
261
+ **每张图片大小** (估算):
262
+ ```
263
+ 分辨率: 1000px × 2500px (高×宽)
264
+ RGB: 3 channels
265
+ 文件大小: ~200-500KB (取决于压缩)
266
+ 总大小: ~2-5GB
267
+ ```
268
+
269
+ ---
270
+
271
+ ## 常见问题
272
+
273
+ ### Q1: 视频帧数不足怎么办?
274
+
275
+ **A**: 改进版脚本会自动跳过帧数不足的视频,并显示警告。
276
+
277
+ **建议**: 可以:
278
+ 1. 减小 `WINDOW_LEN` (如改为 3)
279
+ 2. 或只使用长视频
280
+
281
+ ### Q2: 为什么需要提取音频?
282
+
283
+ **A**: `preprocess.py` 需要单独的 WAV 文件来生成梅尔频谱图。
284
+
285
+ **解决方案**: `convert_ft_work.py` 会自动使用 ffmpeg 提取音频。
286
+
287
+ ### Q3: 如何只处理部分数据?
288
+
289
+ **A**: 设置 `MAX_SAMPLE` 参数:
290
+
291
+ ```python
292
+ MAX_SAMPLE = 100 # 只处理前100个视频
293
+ ```
294
+
295
+ 或使用改进版脚本的命令行参数(需要自行添加)。
296
+
297
+ ### Q4: 输出的图片格式是什么?
298
+
299
+ **A**: PNG 格式,RGB 色彩空间。
300
+
301
+ **尺寸**:
302
+ - 高度: 1000px (频谱图 500px + 帧 500px)
303
+ - 宽度: 2500px (5帧 × 500px)
304
+
305
+ ### Q5: 能否处理其他数据集?
306
+
307
+ **A**: 可以,但需要:
308
+
309
+ 1. 将数据集转换为 AVLips 格式
310
+ 2. 确保有对应的音频文件
311
+ 3. 修改 `audio_root` 和 `video_root` 参数
312
+
313
+ ### Q6: 处理速度如何?
314
+
315
+ **A**: 取决于:
316
+ - 视频数量
317
+ - 视频长度
318
+ - `N_EXTRACT` 和 `WINDOW_LEN` 参数
319
+ - CPU/GPU 性能
320
+
321
+ **估算**:
322
+ - 1个视频 ~ 1-5秒
323
+ - 1000个视频 ~ 15-80分钟
324
+
325
+ **加速建议**:
326
+ - 使用多进程 (`multiprocessing`)
327
+ - 减小 `N_EXTRACT`
328
+ - 使用更快的硬盘(SSD)
329
+
330
+ ---
331
+
332
+ ## 联系与反馈
333
+
334
+ 如有问题或建议,请提出 Issue 或联系开发者。
335
+
336
+ ---
337
+
338
+ **最后更新**: 2026-06-18
LipFD.yml ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: LipFD
2
+ channels:
3
+ - defaults
4
+ dependencies:
5
+ - _libgcc_mutex=0.1=main
6
+ - _openmp_mutex=5.1=52_gnu
7
+ - bzip2=1.0.8=h5eee18b_6
8
+ - ca-certificates=2026.5.14=h06a4308_0
9
+ - ld_impl_linux-64=2.44=h9e0c5a2_3
10
+ - libffi=3.3=he6710b0_2
11
+ - libgcc=15.2.0=h69a1729_8
12
+ - libgcc-ng=15.2.0=h166f726_8
13
+ - libstdcxx=15.2.0=h39759b7_8
14
+ - libstdcxx-ng=15.2.0=hc03a8fd_8
15
+ - libuuid=1.41.5=h5eee18b_0
16
+ - libxcb=1.17.0=h9b100fa_0
17
+ - libzlib=1.3.2=h47b2149_0
18
+ - ncurses=6.5=h7934f7d_0
19
+ - openssl=1.1.1w=h7f8727e_0
20
+ - packaging=26.0=py310h06a4308_0
21
+ - pip=26.1.1=pyhc872135_1
22
+ - pthread-stubs=0.3=h0ce48e5_1
23
+ - python=3.10.0=h12debd9_5
24
+ - readline=8.3=hc2a1206_0
25
+ - sqlite=3.53.2=h795bf6d_0
26
+ - tk=8.6.15=h54e0aa7_0
27
+ - wheel=0.46.3=py310h06a4308_0
28
+ - xorg-libx11=1.8.12=h9b100fa_1
29
+ - xorg-libxau=1.0.12=h9b100fa_0
30
+ - xorg-libxdmcp=1.1.5=h9b100fa_0
31
+ - xorg-xorgproto=2024.1=h5eee18b_1
32
+ - xz=5.8.2=h448239c_0
33
+ - zlib=1.3.2=h47b2149_0
34
+ - pip:
35
+ - certifi==2026.6.17
36
+ - cffi==2.0.0
37
+ - charset-normalizer==3.4.7
38
+ - contourpy==1.3.2
39
+ - cycler==0.12.1
40
+ - decorator==5.3.1
41
+ - filelock==3.29.4
42
+ - fonttools==4.63.0
43
+ - fsspec==2026.6.0
44
+ - ftfy==6.1.1
45
+ - idna==3.18
46
+ - jinja2==3.1.6
47
+ - kiwisolver==1.5.0
48
+ - librosa==0.10.1
49
+ - llvmlite==0.47.0
50
+ - markupsafe==3.0.3
51
+ - matplotlib==3.8.0
52
+ - mpmath==1.3.0
53
+ - msgpack==1.2.0
54
+ - networkx==3.4.2
55
+ - numba==0.65.1
56
+ - numpy==1.25.2
57
+ - nvidia-cublas-cu12==12.1.3.1
58
+ - nvidia-cuda-cupti-cu12==12.1.105
59
+ - nvidia-cuda-nvrtc-cu12==12.1.105
60
+ - nvidia-cuda-runtime-cu12==12.1.105
61
+ - nvidia-cudnn-cu12==8.9.2.26
62
+ - nvidia-cufft-cu12==11.0.2.54
63
+ - nvidia-curand-cu12==10.3.2.106
64
+ - nvidia-cusolver-cu12==11.4.5.107
65
+ - nvidia-cusparse-cu12==12.1.0.106
66
+ - nvidia-nccl-cu12==2.18.1
67
+ - nvidia-nvjitlink-cu12==12.9.86
68
+ - nvidia-nvtx-cu12==12.1.105
69
+ - opencv-contrib-python==4.8.1.78
70
+ - opencv-python==4.8.1.78
71
+ - pandas==2.3.3
72
+ - pillow==12.2.0
73
+ - platformdirs==4.10.0
74
+ - pycparser==3.0
75
+ - pyparsing==3.3.2
76
+ - python-dateutil==2.9.0.post0
77
+ - pytz==2026.2
78
+ - regex==2026.5.9
79
+ - requests==2.34.2
80
+ - scikit-learn==1.3.1
81
+ - scipy==1.15.3
82
+ - setuptools==69.5.1
83
+ - six==1.17.0
84
+ - soundfile==0.14.0
85
+ - soxr==1.1.0
86
+ - sympy==1.14.0
87
+ - torch==2.1.0
88
+ - torchvision==0.16.0
89
+ - tqdm==4.66.1
90
+ - triton==2.1.0
91
+ - typing-extensions==4.15.0
92
+ - tzdata==2026.2
93
+ - urllib3==2.7.0
94
+ - wcwidth==0.8.1
95
+ prefix: /opt/conda/envs/LipFD
README.md ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # [NeruIPS 2024] Lips Are Lying: Spotting the Temporal Inconsistency between Audio and Visual in Lip-syncing DeepFakes
2
+
3
+ <a href='https://arxiv.org/abs/2401.15668v2'><img alt="Static Badge" src="https://img.shields.io/badge/arXiv-2401.15668v2-grey?style=flat&labelColor=red">
4
+ <a href='https://drive.google.com/file/d/1fEiUo22GBSnWD7nfEwDW86Eiza-pOEJm/view?usp=share_link'><img alt="Static Badge" src="https://img.shields.io/badge/dataset-AVLips-grey?style=flat&labelColor=blue">
5
+
6
+
7
+
8
+ ![headline](README.assets/headline.png)
9
+
10
+ > **Abstract.** In recent years, DeepFake technology has achieved unprecedented success in high-quality video synthesis, but these methods also pose potential and severe security threats to humanity. DeepFake can be bifurcated into entertainment applications like face swapping and illicit uses such as lip-syncing fraud. However, lip-forgery videos, which neither change identity nor have discernible visual artifacts, present a formidable challenge to existing DeepFake detection methods. Our preliminary experiments have shown that the effectiveness of the existing methods often drastically decrease or even fail when tackling lip-syncing videos.
11
+ > In this paper, for the first time, we propose a novel approach dedicated to lip-forgery identification that exploits the inconsistency between lip movements and audio signals. We also mimic human natural cognition by capturing subtle biological links between lips and head regions to boost accuracy. To better illustrate the effectiveness and advances of our proposed method, we create a high-quality LipSync dataset, AVLips, by employing the state-of-the-art lip generators. We hope this high-quality and diverse dataset could be well served the further research on this challenging and interesting field. Experimental results show that our approach gives an average accuracy of more than 95.3% in spotting lip-syncing videos, significantly outperforming the baselines. Extensive experiments demonstrate the capability to tackle deepfakes and the robustness in surviving diverse input transformations. Our method achieves an accuracy of up to 90.2% in real-world scenarios (e.g., WeChat video call) and shows its powerful capabilities in real scenario deployment.
12
+
13
+ ![pipeline](README.assets/pipeline.png)
14
+
15
+
16
+
17
+ ## 🔥 AVLips: A high-quality audio-visual dataset for LipSync detection
18
+
19
+ To the best of our knowledge, the majority of public DeepFake datasets consist solely of videos or images, with no specialized one specifically dedicated to LipSync detection available. To fill this gap, we construct a high-quality **A**udio-**V**isual **Lip**-syncing Dataset, **AVLips**, which contains up to 340,000 audio-visual samples generated by several SOTA LipSync methods. The workflow is demonstrated below.
20
+
21
+ **High quality.** We employed a combination of static MakeItTalk and dynamic Wav2Lip, TalkLip, SadTalker generation methods to simulate realistic lip movements. These methods are widely recognized as high-quality work, capable of generating high-resolution videos while ensuring accurate lip movements. We applied a noise reduction algorithm to all audio samples before synthesis to reduce irrelevant background noise, ensuring the models can focus on speech content.
22
+
23
+ **Diversity.** Our dataset encompasses a wide range of scenarios, covering not only well-known public datasets but also real-world data. Our aim is for this collection to act as a catalyst for advancing real-time forgery detection. To better simulate the nuances of real-world conditions, we have employed six perturbation techniques — saturation, contrast, compression, Gaussian noise, Gaussian blur, and pixelation — at various degrees, thus ensuring the dataset's realism and practical relevance.
24
+
25
+ **Download Link: [AVLips v1.0](https://drive.google.com/file/d/1fEiUo22GBSnWD7nfEwDW86Eiza-pOEJm/view?usp=share_link)**
26
+
27
+ <div align=center><img src="README.assets/dataset.png" width="300"></div>
28
+
29
+
30
+
31
+ ## :gear: ​Requirements
32
+
33
+ ~~~bash
34
+ conda create -n LipFD python==3.10
35
+ conda activate LipFD
36
+ pip install -r requirements.txt
37
+ ~~~
38
+
39
+
40
+
41
+ ## :wrench: Dataset Preprocess
42
+
43
+ **You can skip this section, if you only want to perform validation.**
44
+
45
+ Download AVLips dataset and put it in the root directory.
46
+
47
+ AVLips dataset folder structure.
48
+
49
+ ~~~
50
+ AVLips
51
+ ├── 0_real
52
+ │   ├── 0.mp4
53
+ │   ...
54
+ ├── 1_fake
55
+ │   ├── 0.mp4
56
+ │   └── ...
57
+ └── wav
58
+ ├── 0_real
59
+ │   ├── 0.wav
60
+ │   └── ...
61
+ └── 1_fake
62
+ ├── 0.wav
63
+ └── ...
64
+ ~~~
65
+
66
+ Preprocess the dataset for training.
67
+
68
+ ~~~bash
69
+ python preprocess.py
70
+ ~~~
71
+
72
+ Preprocessed AVLips dataset folder structure.
73
+
74
+ ~~~bash
75
+ datasets
76
+ └── AVLips
77
+    ├── 0_real
78
+    │   ├── 0_0.png
79
+    │   └── ...
80
+    └── 1_fake
81
+    ├── 0_0.png
82
+    └── ...
83
+ ~~~
84
+
85
+ The data sample is showed as follow, and **the fully processed dataset is approximately 60 GB.**
86
+
87
+ ![image-20241004221023777](README.assets/image-20241004221023777.png)
88
+
89
+
90
+
91
+ ## :tada: Validation
92
+
93
+ - Download our [pertained weights](https://drive.google.com/file/d/1NPAcx0QS8N9v_9qUr-51jBaL9kGDT-cp/view?usp=share_link) and save it in to `checkpoints/ckpt.pth`.
94
+
95
+ - Download [validation set](https://drive.google.com/file/d/1gZjzps5_rbr6CeBqBke8l2Gs8xXx_Ctb/view?usp=share_link) and extract it into `datasets/val`.
96
+
97
+ ~~~bash
98
+ python validate.py --real_list_path ./datasets/val/0_real --fake_list_path ./datasets/val/1_fake --ckpt ./checkpoints/ckpt.pth
99
+ ~~~
100
+
101
+
102
+
103
+ ## :rocket: Train
104
+
105
+ First, edit `--fake_list_path` and `--real_list_path` in `options/base_options.py`.
106
+
107
+ Then, run `python train.py`.
108
+
109
+
110
+
111
+ ## :mailbox: Citation
112
+
113
+ If you find this repo useful for your research, please consider citing our work:
114
+
115
+ ~~~
116
+ @inproceedings{liu2024lips,
117
+ author = {Liu, Weifeng and She, Tianyi and Liu, Jiawei and Li, Boheng and Yao, Dongyu and Liang, Ziyou and Wang, Run},
118
+ booktitle = {Advances in Neural Information Processing Systems},
119
+ editor = {A. Globerson and L. Mackey and D. Belgrave and A. Fan and U. Paquet and J. Tomczak and C. Zhang},
120
+ pages = {91131--91155},
121
+ publisher = {Curran Associates, Inc.},
122
+ title = {Lips Are Lying: Spotting the Temporal Inconsistency between Audio and Visual in Lip-Syncing DeepFakes},
123
+ url = {https://proceedings.neurips.cc/paper_files/paper/2024/file/a5a5b0ff87c59172a13342d428b1e033-Paper-Conference.pdf},
124
+ volume = {37},
125
+ year = {2024}
126
+ }
127
+ ~~~
README_CONVERT.md ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FT_work 数据集转换指南
2
+
3
+ ## 参数说明
4
+
5
+ 在 `preprocess.py` 中,有三个重要参数:
6
+
7
+ ### 1. N_EXTRACT = 10
8
+ **含义**: 从每个视频中提取的**窗口数量**
9
+
10
+ **工作流程**:
11
+ - 代码会在视频的总帧数中均匀选择 10 个起始点
12
+ - 每个起始点会提取一个连续的帧窗口
13
+ - 例如:视频有 300 帧,会随机选择 10 个起始位置(如帧 0, 33, 66, 99, ...)
14
+
15
+ ### 2. WINDOW_LEN = 5
16
+ **含义**: 每个窗口包含的**连续帧数**
17
+
18
+ **工作流程**:
19
+ - 从每个起始点开始,连续提取 5 帧图像
20
+ - 这 5 帧会拼接成一张宽图(水平拼接)
21
+ - 例如:起始帧为 0,则提取帧 0, 1, 2, 3, 4
22
+
23
+ ### 3. MAX_SAMPLE = 100
24
+ **含义**: 限制的**最大视频处理数量**(按代码逻辑,实际是限制处理的类别数)
25
+
26
+ **注意**: 代码中的实现有点问题,这个参数可能不能按预期工作。建议设置为更大的值或删除这个限制。
27
+
28
+ ---
29
+
30
+ ## 输出示例
31
+
32
+ 假设有一个视频 `video_001.mp4`,包含 300 帧:
33
+
34
+ 1. **选择起始点**: 10 个起始点 = [0, 33, 66, 99, 132, 165, 198, 231, 264, 297]
35
+ 2. **提取窗口**: 每个起始点提取 5 帧
36
+ - 窗口 1: 帧 [0, 1, 2, 3, 4]
37
+ - 窗口 2: 帧 [33, 34, 35, 36, 37]
38
+ - ...
39
+ - 窗口 10: 帧 [297, 298, 299, 300, 301] (如果超出会报错)
40
+ 3. **生成输出**: 每个窗口生成一张图片
41
+ - `video_001_0.png`: 包含窗口1的5帧图像 + 对应音频频谱图
42
+ - `video_001_1.png`: 包含窗口2的5帧图像 + 对应音频频谱图
43
+ - ...
44
+ - `video_001_9.png`: 包含窗口10的5帧图像 + 对应音频频谱图
45
+
46
+ **每个输出图片的格式**:
47
+ - 上半部分: 音频频谱图(时间轴对应这5帧的时间)
48
+ - 下半部分: 5帧图像水平拼接(500x500 每帧,总宽 2500px)
49
+
50
+ ---
51
+
52
+ ## 使用步骤
53
+
54
+ ### 步骤 1: 转换数据集格式
55
+
56
+ 运行转换脚本,将 FT_work 数据集转换为 AVLips 格式:
57
+
58
+ ```bash
59
+ cd /apdcephfs_gy4/share_303628665/joywu/research/LipFD
60
+ python convert_ft_work.py
61
+ ```
62
+
63
+ 这将创建 `./AVLips/` 目录,包含:
64
+ ```
65
+ AVLips/
66
+ ├── 0_real/*.mp4 # 真实视频
67
+ ├── 1_fake/*.mp4 # 假视频
68
+ └── wav/
69
+ ├── 0_real/*.wav # 真实视频的音频
70
+ └── 1_fake/*.wav # 假视频的音频
71
+ ```
72
+
73
+ ### 步骤 2: 修改 preprocess.py 参数
74
+
75
+ 根据你的需求调整参数:
76
+
77
+ ```python
78
+ ############ Custom parameter ##############
79
+ N_EXTRACT = 10 # 每个视频提取10个窗口
80
+ WINDOW_LEN = 5 # 每个窗口5帧
81
+ MAX_SAMPLE = 1000 # 增加这个值以处理更多视频(或设为0表示不限制)
82
+ ############################################
83
+
84
+ audio_root = "./AVLips/wav"
85
+ video_root = "./AVLips"
86
+ output_root = "./datasets/AVLips"
87
+ ```
88
+
89
+ ### 步骤 3: 运行预处理
90
+
91
+ ```bash
92
+ python preprocess.py
93
+ ```
94
+
95
+ ---
96
+
97
+ ## 计算输出数量
98
+
99
+ 如果你有 N 个视频,那么:
100
+
101
+ - **总输出图片数** = N × N_EXTRACT
102
+ - **每个视频的输出数** = N_EXTRACT = 10 张图片
103
+ - **每张图片包含的帧数** = WINDOW_LEN = 5 帧
104
+
105
+ 例如:
106
+ - 100 个视频 → 100 × 10 = 1000 张输出图片
107
+ - 1000 个视频 → 1000 × 10 = 10000 张输出图片
108
+
109
+ ---
110
+
111
+ ## 注意事项
112
+
113
+ 1. **视频帧数要求**: 视频至少需要 `WINDOW_LEN` 帧(5帧),否则会报错
114
+ 2. **音频提取**: 需要安装 ffmpeg (`pip install ffmpeg-python` 或系统安装 ffmpeg)
115
+ 3. **磁盘空间**: 输出图片可能很大(每张约 500x3000 像素),确保有足够空间
116
+ 4. **处理时间**: 每个视频需要提取音频、读取帧、生成频谱图,可能需要较长时间
117
+
118
+ ---
119
+
120
+ ## 自定义调整
121
+
122
+ 如果你想修改提取策略,可以调整以下代码(在 `preprocess.py` 的第 47-52 行):
123
+
124
+ ```python
125
+ # 原始:均匀选择起始点
126
+ frame_idx = np.linspace(
127
+ 0,
128
+ frame_count - WINDOW_LEN - 1,
129
+ N_EXTRACT,
130
+ endpoint=True,
131
+ dtype=np.uint8,
132
+ ).tolist()
133
+
134
+ # 改为:随机选择起始点(可能更有代表性)
135
+ frame_idx = np.random.choice(
136
+ frame_count - WINDOW_LEN,
137
+ size=N_EXTRACT,
138
+ replace=False
139
+ ).tolist()
140
+ ```
__pycache__/utils.cpython-310.pyc ADDED
Binary file (523 Bytes). View file
 
__pycache__/validate.cpython-310.pyc ADDED
Binary file (2.62 kB). View file
 
_diag_perturb.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Diagnostic: for one real test image, apply each perturbation at L5, then
2
+ - report pixel-level diff stats on the perturbed strip,
3
+ - crop the SAME way data.AVLip does, report diff stats on what the model
4
+ actually sees,
5
+ - save side-by-side PNGs to robustnessv3/_diag/."""
6
+ import os
7
+ import sys
8
+ import numpy as np
9
+ import cv2
10
+ import torch
11
+ import torchvision.transforms as T
12
+
13
+ sys.path.insert(0, "/apdcephfs_gy4/share_303628665/joywu/research/LipFD")
14
+ from evaluate_robustness import perturb_bgr, SEVERITY
15
+
16
+ OUT = "/apdcephfs_gy4/share_303628665/joywu/research/LipFD/robustnessv3/_diag"
17
+ os.makedirs(OUT, exist_ok=True)
18
+
19
+ img_path = "/apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/test/0_real/2358_Real_CelebV-HQ_0.png"
20
+ img_cv = cv2.imread(img_path)
21
+ print(f"loaded: {img_cv.shape} {img_cv.dtype} min={img_cv.min()} max={img_cv.max()}")
22
+ H, W = img_cv.shape[:2]
23
+ print(f"H={H} W={W}")
24
+
25
+ # Same crop logic as data.AVLip / validate.py
26
+ def lipfd_crops(img_uint8):
27
+ """Replicates data/datasets.py:25-71. Returns list of crops the model sees."""
28
+ img = torch.tensor(img_uint8, dtype=torch.float32).permute(2, 0, 1) # (3, H, W)
29
+ # Note the slicing: img[:, 500:, i:i+500] for i in range(5)
30
+ # range(5) => i = 0,1,2,3,4 — so 5 crops are NEARLY THE SAME, shifted by 1 px.
31
+ base_crops = [img[:, 500:, i:i + 500] for i in range(5)]
32
+ return [c.numpy().astype(np.uint8).transpose(1, 2, 0) for c in base_crops]
33
+
34
+ clean_strip = img_cv[500:, :, :].copy()
35
+ clean_crops = lipfd_crops(img_cv)
36
+ print(f"\nclean: bottom strip shape={clean_strip.shape} -> 5 crops of shape {clean_crops[0].shape}")
37
+
38
+ print(f"\n5 crop offsets (i in range(5) → cols i:i+500): only LEFT {500+4}={504} of {W} cols ever reach model")
39
+ print(f" crop0 covers cols 0:500, crop1 covers cols 1:501, ..., crop4 covers cols 4:504")
40
+ print(f" crops are nearly IDENTICAL — model effectively sees 1 region, not 5 spatial faces\n")
41
+
42
+ print("="*100)
43
+ print(f"{'perturbation':<18} {'L5 param':>10} {'strip Δ mean abs':>18} {'strip max diff':>14} {'crop0 Δ mean abs':>18}")
44
+ print("-"*100)
45
+ for p in ["color_saturation", "color_contrast", "block_wise", "gaussian_noise",
46
+ "gaussian_blur", "pixelate", "jpeg_quality"]:
47
+ perturbed_strip = perturb_bgr(clean_strip, p, 5, base_seed=42)
48
+ diff_strip = np.abs(perturbed_strip.astype(int) - clean_strip.astype(int))
49
+
50
+ img_pert = img_cv.copy()
51
+ img_pert[500:, :, :] = perturbed_strip
52
+ crops_pert = lipfd_crops(img_pert)
53
+ diff_crop0 = np.abs(crops_pert[0].astype(int) - clean_crops[0].astype(int))
54
+
55
+ print(f"{p:<18} {str(SEVERITY[p][4]):>10} {diff_strip.mean():>18.3f} {diff_strip.max():>14d} {diff_crop0.mean():>18.3f}")
56
+
57
+ # save side-by-side png for visual check (resize for compactness)
58
+ side = np.concatenate([clean_strip, perturbed_strip], axis=0)
59
+ side_small = cv2.resize(side, (1000, 400))
60
+ cv2.imwrite(f"{OUT}/L5_{p}_strip.png", side_small)
61
+ cv2.imwrite(f"{OUT}/L5_{p}_crop0.png",
62
+ np.concatenate([clean_crops[0], crops_pert[0]], axis=1))
63
+ print("="*100)
64
+ print(f"\nSide-by-side PNGs saved to {OUT}/")
convert_ft_work.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ from tqdm import tqdm
4
+ import librosa
5
+ import soundfile as sf
6
+ import subprocess
7
+
8
+ """
9
+ 将FT_work数据集转换为AVLips格式
10
+
11
+ FT_work原始结构:
12
+ videos/
13
+ ├── train/
14
+ │ ├── real/Real/*.mp4
15
+ │ └── fake/{AniPortrait,Joyvasa,Ditto,Hallo,Sonic}/*.mp4
16
+ ├── test/
17
+ │ ├── real/Real/*.mp4
18
+ │ └── fake/{SadTalk,EDTalk,Float}/*.mp4
19
+ └── val/
20
+ ├── real/Real/*.mp4
21
+ └── fake/{AniPortrait,Joyvasa,Ditto,Hallo,Sonic}/*.mp4
22
+
23
+ 目标AVLips结构:
24
+ AVLips/
25
+ ├── 0_real/*.mp4
26
+ ├── 1_fake/*.mp4
27
+ └── wav/
28
+ ├── 0_real/*.wav
29
+ └── 1_fake/*.wav
30
+
31
+ 注意:需要先从视频中提取音频
32
+ """
33
+
34
+ # 配置参数
35
+ FT_WORK_ROOT = "/apdcephfs_gy5/share_303628665/joyewu/dataset/FT_work"
36
+ OUTPUT_ROOT = "./AVLips" # 输出为AVLips格式
37
+ EXTRACT_AUDIO = True # 是否从视频中提取音频
38
+
39
+
40
+ def extract_audio_from_video(video_path, audio_path):
41
+ """使用ffmpeg从视频中提取音频"""
42
+ try:
43
+ cmd = [
44
+ "ffmpeg", "-i", video_path,
45
+ "-vn", # 不要视频
46
+ "-acodec", "pcm_s16le", # WAV格式
47
+ "-ar", "16000", # 采样率16kHz(librosa默认)
48
+ "-ac", "1", # 单声道
49
+ "-y", # 覆盖已存在文件
50
+ audio_path
51
+ ]
52
+ subprocess.run(cmd, capture_output=True, check=True)
53
+ return True
54
+ except subprocess.CalledProcessError as e:
55
+ print(f"音频提取失败: {video_path}")
56
+ print(f"错误: {e.stderr.decode() if e.stderr else 'Unknown error'}")
57
+ return False
58
+ except Exception as e:
59
+ print(f"音频提取异常: {video_path}")
60
+ print(f"错误: {str(e)}")
61
+ return False
62
+
63
+
64
+ def process_split(split_name, output_video_real, output_video_fake, output_audio_real, output_audio_fake):
65
+ """
66
+ 处理一个数据集分割(train/test/val)
67
+
68
+ Args:
69
+ split_name: 分割名称 ('train', 'test', 'val')
70
+ output_video_real: 输出真实视频目录
71
+ output_video_fake: 输出假视频目录
72
+ output_audio_real: 输出真实音频目录
73
+ output_audio_fake: 输出假音频目录
74
+ """
75
+ split_path = os.path.join(FT_WORK_ROOT, "videos", split_name)
76
+
77
+ if not os.path.exists(split_path):
78
+ print(f"警告: {split_path} 不存在,跳过")
79
+ return
80
+
81
+ # 处理真实视频
82
+ real_path = os.path.join(split_path, "real", "Real")
83
+ if os.path.exists(real_path):
84
+ print(f"\n处理 {split_name}/real...")
85
+ video_files = [f for f in os.listdir(real_path) if f.endswith('.mp4')]
86
+
87
+ for video_file in tqdm(video_files, desc="真实视频"):
88
+ src_video = os.path.join(real_path, video_file)
89
+ dst_video = os.path.join(output_video_real, video_file)
90
+
91
+ # 复制视频文件
92
+ if not os.path.exists(dst_video):
93
+ shutil.copy2(src_video, dst_video)
94
+
95
+ # 提取音频
96
+ if EXTRACT_AUDIO:
97
+ audio_file = video_file.replace('.mp4', '.wav')
98
+ dst_audio = os.path.join(output_audio_real, audio_file)
99
+ if not os.path.exists(dst_audio):
100
+ extract_audio_from_video(src_video, dst_audio)
101
+
102
+ # 处理假视频
103
+ fake_path = os.path.join(split_path, "fake")
104
+ if os.path.exists(fake_path):
105
+ print(f"\n处理 {split_name}/fake...")
106
+ fake_methods = os.listdir(fake_path)
107
+
108
+ for method in fake_methods:
109
+ method_path = os.path.join(fake_path, method)
110
+ if not os.path.isdir(method_path):
111
+ continue
112
+
113
+ video_files = [f for f in os.listdir(method_path) if f.endswith('.mp4')]
114
+
115
+ for video_file in tqdm(video_files, desc=f"假视频/{method}"):
116
+ src_video = os.path.join(method_path, video_file)
117
+
118
+ # 为了避免文件名冲突,添加方法前缀
119
+ new_name = f"{method}_{video_file}"
120
+ dst_video = os.path.join(output_video_fake, new_name)
121
+
122
+ # 复制视频文件
123
+ if not os.path.exists(dst_video):
124
+ shutil.copy2(src_video, dst_video)
125
+
126
+ # 提取音频
127
+ if EXTRACT_AUDIO:
128
+ audio_file = new_name.replace('.mp4', '.wav')
129
+ dst_audio = os.path.join(output_audio_fake, audio_file)
130
+ if not os.path.exists(dst_audio):
131
+ extract_audio_from_video(src_video, dst_audio)
132
+
133
+
134
+ def main():
135
+ # 创建输出目录结构
136
+ print("创建输出目录结构...")
137
+ dirs = [
138
+ os.path.join(OUTPUT_ROOT, "0_real"),
139
+ os.path.join(OUTPUT_ROOT, "1_fake"),
140
+ os.path.join(OUTPUT_ROOT, "wav", "0_real"),
141
+ os.path.join(OUTPUT_ROOT, "wav", "1_fake"),
142
+ ]
143
+
144
+ for d in dirs:
145
+ os.makedirs(d, exist_ok=True)
146
+ print(f" 创建: {d}")
147
+
148
+ # 处理各个分割
149
+ splits = ['train', 'test', 'val']
150
+
151
+ for split in splits:
152
+ print(f"\n{'='*50}")
153
+ print(f"处理分割: {split}")
154
+ print(f"{'='*50}")
155
+
156
+ process_split(
157
+ split_name=split,
158
+ output_video_real=os.path.join(OUTPUT_ROOT, "0_real"),
159
+ output_video_fake=os.path.join(OUTPUT_ROOT, "1_fake"),
160
+ output_audio_real=os.path.join(OUTPUT_ROOT, "wav", "0_real"),
161
+ output_audio_fake=os.path.join(OUTPUT_ROOT, "wav", "1_fake")
162
+ )
163
+
164
+ print(f"\n{'='*50}")
165
+ print("转换完成!")
166
+ print(f"{'='*50}")
167
+ print(f"\n输出目录: {OUTPUT_ROOT}")
168
+ print(f"目录结构:")
169
+ print(f"├── 0_real/ ({len(os.listdir(os.path.join(OUTPUT_ROOT, '0_real')))} 个视频)")
170
+ print(f"├── 1_fake/ ({len(os.listdir(os.path.join(OUTPUT_ROOT, '1_fake')))} 个视频)")
171
+ print(f"└── wav/")
172
+ print(f" ├── 0_real/ ({len(os.listdir(os.path.join(OUTPUT_ROOT, 'wav', '0_real')))} 个音频)")
173
+ print(f" └── 1_fake/ ({len(os.listdir(os.path.join(OUTPUT_ROOT, 'wav', '1_fake')))} 个音频)")
174
+
175
+
176
+ if __name__ == "__main__":
177
+ main()
evaluate_robustness.py ADDED
@@ -0,0 +1,621 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """evaluate_robustness.py
2
+
3
+ Run robustness evaluation on LipFD: in-memory perturb the bottom face strip
4
+ (rows 500: of the 1000x2500 composite) and re-evaluate AUROC / per-fake-vs-real /
5
+ fairness. ZERO additional disk: perturbation is applied inside __getitem__,
6
+ only the metrics JSON is written.
7
+
8
+ Perturbation set (paper-aligned, 7 frame-level subset):
9
+ color_saturation | color_contrast | block_wise | gaussian_noise |
10
+ gaussian_blur | pixelate | jpeg_quality
11
+ Levels: 1..5 (level 1 = no-op for all 7 in SEVERITY, level 5 = heaviest).
12
+
13
+ Aggregation: clip-level by basename (e.g. '2358_Real', '1681_Fake').
14
+ Demographics (gender / race4 / age_group) joined from a CSV that maps
15
+ basename -> demo attributes.
16
+
17
+ ============================================================================
18
+ Commands actually executed in this session (cwd = /apdcephfs_gy4/share_303628665/joywu/research/LipFD)
19
+ ============================================================================
20
+ # (a) Smoke test 1 — level=1 (no-op) clean baseline:
21
+ # /opt/conda/envs/LipFD/bin/python evaluate_robustness.py \
22
+ # --real_list_path datasets/FairTalking-Bench/test/0_real \
23
+ # --fake_list_path datasets/FairTalking-Bench/test/1_fake \
24
+ # --ckpt checkpoints/lipfd_train/model_epoch_44.pth \
25
+ # --demographics_csv /apdcephfs_gy4/share_303628665/joywu/research/test.csv \
26
+ # --perturbation gaussian_noise --level 1 \
27
+ # --batch_size 16 --loader_workers 4 --gpu 0 \
28
+ # --save_json /apdcephfs_gy4/share_303628665/joywu/research/LipFD/robustness/runs.json
29
+ # -> overall_clip AUROC=0.9958 AP=0.9956 Acc=0.9484 n_clips=581 n_samples=11610
30
+ #
31
+ # (b) Smoke test 2 — gaussian_noise level=3 (verify perturbation actually bites):
32
+ # /opt/conda/envs/LipFD/bin/python evaluate_robustness.py \
33
+ # --real_list_path datasets/FairTalking-Bench/test/0_real \
34
+ # --fake_list_path datasets/FairTalking-Bench/test/1_fake \
35
+ # --ckpt checkpoints/lipfd_train/model_epoch_44.pth \
36
+ # --demographics_csv /apdcephfs_gy4/share_303628665/joywu/research/test.csv \
37
+ # --perturbation gaussian_noise --level 3 \
38
+ # --batch_size 16 --loader_workers 4 --gpu 0 \
39
+ # --save_json /apdcephfs_gy4/share_303628665/joywu/research/LipFD/robustness/runs.json
40
+ # -> overall_clip AUROC=0.9772 (down 0.019) TPR@1%FPR=0.4966 (down 0.34) — perturbation works
41
+ #
42
+ # (c) Full sweep (7 perturbations x 5 levels = 35 combos, level=1 only run once):
43
+ # nohup bash run_robustness.sh > robustness/sweep.log 2>&1 &
44
+ # # run_robustness.sh internally calls this script 29 times (1 baseline + 7*4 levels),
45
+ # # appending each run to robustness/runs.json. ~2.7h on a single 100GB-class GPU.
46
+
47
+ Usage (single perturbation x level):
48
+ python evaluate_robustness.py \
49
+ --real_list_path datasets/FairTalking-Bench/test/0_real \
50
+ --fake_list_path datasets/FairTalking-Bench/test/1_fake \
51
+ --ckpt checkpoints/lipfd_train/model_epoch_44.pth \
52
+ --demographics_csv /apdcephfs_gy4/share_303628665/joywu/research/test.csv \
53
+ --perturbation gaussian_noise --level 3 \
54
+ --save_json robustness/runs.json
55
+ """
56
+
57
+ import argparse
58
+ import collections
59
+ import csv as _csv
60
+ import json
61
+ import math
62
+ import os
63
+ import random as _rng_mod
64
+ import re
65
+ import sys
66
+ import time
67
+
68
+ import cv2
69
+ import numpy as np
70
+ import torch
71
+ import torchvision.transforms as transforms
72
+ from sklearn.metrics import (
73
+ accuracy_score,
74
+ average_precision_score,
75
+ classification_report,
76
+ confusion_matrix,
77
+ roc_auc_score,
78
+ roc_curve,
79
+ )
80
+ from torch.utils.data import DataLoader, Dataset
81
+ from tqdm import tqdm
82
+
83
+ _REPO_ROOT = os.path.dirname(os.path.abspath(__file__))
84
+ sys.path.insert(0, _REPO_ROOT)
85
+
86
+ from models import build_model # noqa: E402
87
+ import utils as _u # noqa: E402
88
+
89
+
90
+ # ============================================================================
91
+ # Perturbation parameters — verbatim from X-AVDT/train/evaluate_robustness.py
92
+ # (originally from AVH-Align/robustness/distortions.py).
93
+ # ============================================================================
94
+ SEVERITY = {
95
+ "color_saturation": [1.0, 0.8, 1.2, 1.5, 2.0],
96
+ "color_contrast": [1.0, 0.85, 1.2, 1.4, 1.6],
97
+ "block_wise": [0, 8, 16, 24, 32],
98
+ "gaussian_noise": [0.0, 0.001, 0.005, 0.01, 0.05],
99
+ "gaussian_blur": [1, 3, 7, 11, 15],
100
+ "pixelate": [1, 2, 4, 6, 8],
101
+ "jpeg_quality": [100, 85, 70, 50, 30],
102
+ }
103
+ PERTURBATIONS = list(SEVERITY.keys())
104
+ DEMO_DIMS = ("gender", "race4", "age_group")
105
+
106
+
107
+ # ----- frame-level perturbation primitives (BGR uint8) -----
108
+ def _bgr2ycbcr(img_bgr):
109
+ img = img_bgr.astype(np.float32) / 255.0
110
+ M = np.array([
111
+ [ 0.299, 0.587, 0.114],
112
+ [-0.16874, -0.33126, 0.5],
113
+ [ 0.5, -0.41869, -0.08131],
114
+ ], dtype=np.float32)
115
+ yuv = img @ M.T
116
+ yuv[..., 1:] += 0.5
117
+ return yuv
118
+
119
+
120
+ def _ycbcr2bgr(ycbcr):
121
+ yuv = ycbcr.copy()
122
+ yuv[..., 1:] -= 0.5
123
+ M = np.array([
124
+ [1.0, 0.0, 1.402],
125
+ [1.0, -0.34414, -0.71414],
126
+ [1.0, 1.772, 0.0],
127
+ ], dtype=np.float32)
128
+ return np.clip(yuv @ M.T * 255.0, 0, 255)
129
+
130
+
131
+ def _apply_color_saturation(b, p):
132
+ if abs(p - 1.0) < 1e-6:
133
+ return b
134
+ y = _bgr2ycbcr(b)
135
+ y[..., 1] = 0.5 + (y[..., 1] - 0.5) * p
136
+ y[..., 2] = 0.5 + (y[..., 2] - 0.5) * p
137
+ return np.clip(_ycbcr2bgr(y), 0, 255).astype(np.uint8)
138
+
139
+
140
+ def _apply_color_contrast(b, p):
141
+ if abs(p - 1.0) < 1e-6:
142
+ return b
143
+ return np.clip(b.astype(np.float32) * p, 0, 255).astype(np.uint8)
144
+
145
+
146
+ def _apply_block_wise(b, p, rng):
147
+ if p <= 0:
148
+ return b
149
+ width = 8
150
+ block = np.ones((width, width, 3), dtype=np.uint8) * 128
151
+ n = max(1, min(b.shape[0], b.shape[1]) // 256 * int(p))
152
+ out = b.copy()
153
+ H, W = b.shape[:2]
154
+ for _ in range(n):
155
+ rw = rng.randint(0, W - 1 - width)
156
+ rh = rng.randint(0, H - 1 - width)
157
+ out[rh:rh + width, rw:rw + width, :] = block
158
+ return out
159
+
160
+
161
+ def _apply_gaussian_noise(b, p, rng_np):
162
+ if p <= 0:
163
+ return b
164
+ y = _bgr2ycbcr(b)
165
+ h, w, c = y.shape
166
+ noise = math.sqrt(p) * rng_np.standard_normal((h, w, c)).astype(np.float32)
167
+ return np.clip(_ycbcr2bgr(y + noise), 0, 255).astype(np.uint8)
168
+
169
+
170
+ def _apply_gaussian_blur(b, k):
171
+ k = int(k)
172
+ if k <= 1:
173
+ return b
174
+ if k % 2 == 0:
175
+ k += 1
176
+ return cv2.GaussianBlur(b, (k, k), k / 6.0)
177
+
178
+
179
+ def _apply_pixelate(b, f):
180
+ f = int(f)
181
+ if f <= 1:
182
+ return b
183
+ h, w = b.shape[:2]
184
+ sw, sh = max(1, w // f), max(1, h // f)
185
+ small = cv2.resize(b, (sw, sh), interpolation=cv2.INTER_AREA)
186
+ return cv2.resize(small, (w, h), interpolation=cv2.INTER_LINEAR)
187
+
188
+
189
+ def _apply_jpeg(b, q):
190
+ q = int(q)
191
+ if q >= 100:
192
+ return b
193
+ ok, buf = cv2.imencode(".jpg", b, [int(cv2.IMWRITE_JPEG_QUALITY), q])
194
+ if not ok:
195
+ return b
196
+ dec = cv2.imdecode(buf, cv2.IMREAD_COLOR)
197
+ return dec if dec is not None else b
198
+
199
+
200
+ def perturb_bgr(bgr_uint8, perturbation, level, base_seed=42):
201
+ """Apply perturbation to a single BGR uint8 region. Returns BGR uint8."""
202
+ param = SEVERITY[perturbation][level - 1]
203
+ seed = (hash((base_seed, perturbation, level)) & 0xFFFFFFFF)
204
+ py_rng = _rng_mod.Random(seed)
205
+ np_rng = np.random.RandomState(seed)
206
+ if perturbation == "color_saturation":
207
+ return _apply_color_saturation(bgr_uint8, param)
208
+ elif perturbation == "color_contrast":
209
+ return _apply_color_contrast(bgr_uint8, param)
210
+ elif perturbation == "block_wise":
211
+ return _apply_block_wise(bgr_uint8, param, py_rng)
212
+ elif perturbation == "gaussian_noise":
213
+ return _apply_gaussian_noise(bgr_uint8, param, np_rng)
214
+ elif perturbation == "gaussian_blur":
215
+ return _apply_gaussian_blur(bgr_uint8, param)
216
+ elif perturbation == "pixelate":
217
+ return _apply_pixelate(bgr_uint8, param)
218
+ elif perturbation == "jpeg_quality":
219
+ return _apply_jpeg(bgr_uint8, param)
220
+ raise ValueError(f"unsupported perturbation: {perturbation}")
221
+
222
+
223
+ # ============================================================================
224
+ # Wrapper Dataset — replicate AVLip preprocessing, perturbing only the bottom
225
+ # face strip (rows 500: of the 1000x2500 composite).
226
+ # ============================================================================
227
+ _BASENAME_RE = re.compile(r"(\d+_(?:Real|Fake))")
228
+
229
+
230
+ def _extract_basename(img_path):
231
+ """'/.../2358_Real_CelebV-HQ_0.png' -> '2358_Real'
232
+ '/.../EDTalk_1681_Fake_EDTalk_0.png' -> '1681_Fake'."""
233
+ m = _BASENAME_RE.search(os.path.basename(img_path))
234
+ return m.group(1) if m else os.path.basename(img_path).rsplit(".", 1)[0]
235
+
236
+
237
+ def _extract_model_id(img_path, label):
238
+ """Real -> 'Real'; fake -> the prefix model name (EDTalk / Float / SadTalk / ...)."""
239
+ if label == 0:
240
+ return "Real"
241
+ return os.path.basename(img_path).split("_", 1)[0]
242
+
243
+
244
+ class PerturbedAVLip(Dataset):
245
+ """Mirrors data.AVLip preprocessing exactly, but perturbs the bottom 500
246
+ rows (face strip) before slicing into crops at 3 scales."""
247
+
248
+ def __init__(self, real_dir, fake_dir, perturbation, level, base_seed=42):
249
+ self.real_list = _u.get_list(real_dir)
250
+ self.fake_list = _u.get_list(fake_dir)
251
+ self.label_dict = {p: 0 for p in self.real_list}
252
+ self.label_dict.update({p: 1 for p in self.fake_list})
253
+ self.total_list = self.real_list + self.fake_list
254
+ self.perturbation = perturbation
255
+ self.level = level
256
+ self.base_seed = base_seed
257
+ self._is_noop = level == 1 # level 1 is no-op for every perturbation
258
+
259
+ def __len__(self):
260
+ return len(self.total_list)
261
+
262
+ def _read_with_skip(self, idx, tried):
263
+ if len(tried) >= len(self.total_list):
264
+ raise RuntimeError("All samples are corrupted or cannot be read!")
265
+ tried.add(idx)
266
+ path = self.total_list[idx]
267
+ if not os.path.exists(path):
268
+ print(f"WARNING: File not found, skipping: {path}")
269
+ return self._read_with_skip((idx + 1) % len(self.total_list), tried)
270
+ img_cv = cv2.imread(path)
271
+ if img_cv is None:
272
+ print(f"WARNING: Failed to read image, skipping: {path}")
273
+ return self._read_with_skip((idx + 1) % len(self.total_list), tried)
274
+ return img_cv, self.label_dict[path], path
275
+
276
+ def __getitem__(self, idx):
277
+ img_cv, label, path = self._read_with_skip(idx, set()) # BGR (H,W,3) uint8
278
+
279
+ # ---- perturb only the bottom face strip (rows 500:) ----
280
+ if not self._is_noop:
281
+ face_strip = img_cv[500:, :, :]
282
+ perturbed = perturb_bgr(face_strip, self.perturbation, self.level, self.base_seed)
283
+ img_cv = img_cv.copy()
284
+ img_cv[500:, :, :] = perturbed
285
+
286
+ # ---- preprocessing — bit-faithful with data/datasets.py:AVLip.__getitem__ ----
287
+ img = torch.tensor(img_cv, dtype=torch.float32).permute(2, 0, 1)
288
+ # NB: original AVLip computes Normalize(img) then immediately overwrites
289
+ # `crops` with un-normalized strips, so the normalize is dead. We omit it.
290
+ # FIX: 5-crop slicing was `i:i+500 for i in range(5)` (5 near-identical
291
+ # 1-px-shifted views of face0); changed to `i*500:(i+1)*500` so 5 distinct
292
+ # 500x500 face patches reach the model. Same fix in data/datasets.py:64.
293
+ crops = [[transforms.Resize((224, 224))(img[:, 500:, i*500:(i+1)*500]) for i in range(5)], [], []]
294
+ crop_idx = [(28, 196), (61, 163)]
295
+ for i in range(len(crops[0])):
296
+ crops[1].append(transforms.Resize((224, 224))(
297
+ crops[0][i][:, crop_idx[0][0]:crop_idx[0][1], crop_idx[0][0]:crop_idx[0][1]]))
298
+ crops[2].append(transforms.Resize((224, 224))(
299
+ crops[0][i][:, crop_idx[1][0]:crop_idx[1][1], crop_idx[1][0]:crop_idx[1][1]]))
300
+ big = transforms.Resize((1120, 1120))(img)
301
+ return big, crops, label, path
302
+
303
+
304
+ def custom_collate(batch):
305
+ """Same collate as validate.py — flattens the (scales x crops) list-of-tensors
306
+ into per-(scale, crop) batched tensors of shape (B, 3, 224, 224)."""
307
+ imgs = torch.stack([item[0] for item in batch])
308
+ num_scales = len(batch[0][1])
309
+ num_crops = len(batch[0][1][0])
310
+ crops = []
311
+ for s in range(num_scales):
312
+ scale_crops = []
313
+ for c in range(num_crops):
314
+ tensors = [batch[i][1][s][c] for i in range(len(batch))]
315
+ scale_crops.append(torch.stack(tensors))
316
+ crops.append(scale_crops)
317
+ labels = torch.tensor([item[2] for item in batch])
318
+ paths = [item[3] for item in batch]
319
+ return imgs, crops, labels, paths
320
+
321
+
322
+ # ============================================================================
323
+ # metric helpers (X-AVDT-compatible)
324
+ # ============================================================================
325
+ def _tpr_at_fpr(y_true, y_score, fpr_target):
326
+ fpr, tpr, _ = roc_curve(y_true, y_score)
327
+ if (fpr <= fpr_target).any():
328
+ return float(tpr[fpr <= fpr_target].max())
329
+ return 0.0
330
+
331
+
332
+ def _compute_eer_threshold(y_true, y_score):
333
+ fpr, tpr, thresholds = roc_curve(y_true, y_score)
334
+ fnr = 1 - tpr
335
+ return float(thresholds[int(np.argmin(np.abs(fpr - fnr)))])
336
+
337
+
338
+ def _metrics_block(y_true, y_score, threshold=0.5):
339
+ y_true = np.asarray(y_true)
340
+ y_score = np.asarray(y_score)
341
+ y_pred = (y_score >= threshold).astype(int)
342
+
343
+ out = {}
344
+ try:
345
+ out["AUROC"] = float(roc_auc_score(y_true, y_score))
346
+ except Exception:
347
+ out["AUROC"] = None
348
+ try:
349
+ out["AP"] = float(average_precision_score(y_true, y_score))
350
+ except Exception:
351
+ out["AP"] = None
352
+ out[f"Accuracy@{threshold:.2f}"] = float(accuracy_score(y_true, y_pred))
353
+ out["Confusion Matrix"] = confusion_matrix(y_true, y_pred, labels=[0, 1]).tolist()
354
+ out["Classification Report"] = classification_report(
355
+ y_true, y_pred, labels=[0, 1], output_dict=True, zero_division=0
356
+ )
357
+ try:
358
+ thr = _compute_eer_threshold(y_true, y_score)
359
+ out["EER_threshold"] = thr
360
+ out["Acc@EER"] = float(accuracy_score(y_true, (y_score >= thr).astype(int)))
361
+ except Exception:
362
+ out["EER_threshold"] = None
363
+ out["Acc@EER"] = None
364
+ try:
365
+ out["TPR@FPR=1%"] = _tpr_at_fpr(y_true, y_score, 0.01)
366
+ out["TPR@FPR=0.1%"] = _tpr_at_fpr(y_true, y_score, 0.001)
367
+ except Exception:
368
+ out["TPR@FPR=1%"] = None
369
+ out["TPR@FPR=0.1%"] = None
370
+ return out
371
+
372
+
373
+ def _fmt4(v):
374
+ try:
375
+ return f"{float(v):.4f}"
376
+ except Exception:
377
+ return "n/a"
378
+
379
+
380
+ def _set_seed(seed):
381
+ np.random.seed(seed)
382
+ torch.manual_seed(seed)
383
+ if torch.cuda.is_available():
384
+ torch.cuda.manual_seed_all(seed)
385
+ torch.backends.cudnn.deterministic = True
386
+ torch.backends.cudnn.benchmark = False
387
+
388
+
389
+ def load_ckpt(model, ckpt_path):
390
+ ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
391
+ state = ckpt.get("model", ckpt) if isinstance(ckpt, dict) else ckpt
392
+ cleaned = collections.OrderedDict()
393
+ for k, v in state.items():
394
+ if k.startswith("module."):
395
+ k = k[len("module."):]
396
+ cleaned[k] = v
397
+ info = model.load_state_dict(cleaned, strict=False)
398
+ out = {"missing_count": len(info.missing_keys),
399
+ "unexpected_count": len(info.unexpected_keys)}
400
+ if not info.missing_keys and not info.unexpected_keys:
401
+ print(f"[OK] Strict checkpoint match: all {len(cleaned)} keys consumed.")
402
+ else:
403
+ print(f"[WARN] missing={len(info.missing_keys)} unexpected={len(info.unexpected_keys)}")
404
+ return out
405
+
406
+
407
+ def compute_fairness(y_true, y_score, groups):
408
+ y_true = np.asarray(y_true)
409
+ y_score = np.asarray(y_score)
410
+ groups = np.asarray(groups)
411
+ pred = (y_score > 0.5).astype(int)
412
+
413
+ def _g_fpr(g):
414
+ m = (groups == g) & (y_true == 0)
415
+ return float(pred[m].mean()) if m.sum() else 0.0
416
+
417
+ def _g_tpr(g):
418
+ m = (groups == g) & (y_true == 1)
419
+ return float(pred[m].mean()) if m.sum() else 0.0
420
+
421
+ def _g_acc(g):
422
+ m = (groups == g)
423
+ return float((pred[m] == y_true[m]).mean()) if m.sum() else 0.0
424
+
425
+ def _g_dp(g):
426
+ m = (groups == g)
427
+ return float(pred[m].mean()) if m.sum() else 0.0
428
+
429
+ uniq = sorted(set(groups.tolist()))
430
+ if not uniq:
431
+ return None
432
+ fprs = [_g_fpr(g) for g in uniq]
433
+ tprs = [_g_tpr(g) for g in uniq]
434
+ accs = [_g_acc(g) for g in uniq]
435
+ dps = [_g_dp(g) for g in uniq]
436
+ ns = [int((groups == g).sum()) for g in uniq]
437
+ return {
438
+ "F_FPR": float(np.std(fprs)) * 100,
439
+ "F_MEO": (max(max(fprs) - min(fprs), max(tprs) - min(tprs))) * 100,
440
+ "F_DP": float(np.std(dps)) * 100,
441
+ "F_OAE": float(np.std(accs)) * 100,
442
+ "groups": {g: {"n": n, "fpr": f, "tpr": t, "acc": a, "dp": d}
443
+ for g, n, f, t, a, d in zip(uniq, ns, fprs, tprs, accs, dps)},
444
+ }
445
+
446
+
447
+ def load_demographics(csv_path):
448
+ out = {}
449
+ with open(csv_path, newline="") as f:
450
+ for row in _csv.DictReader(f):
451
+ base = row["basename"].strip()
452
+ if base:
453
+ out[base] = {
454
+ "gender": (row.get("gender") or "").strip(),
455
+ "race4": (row.get("race4") or "").strip(),
456
+ "age_group": (row.get("age_group") or "").strip(),
457
+ }
458
+ return out
459
+
460
+
461
+ # ============================================================================
462
+ # main
463
+ # ============================================================================
464
+ def parse_args():
465
+ p = argparse.ArgumentParser()
466
+ p.add_argument("--real_list_path", type=str, required=True)
467
+ p.add_argument("--fake_list_path", type=str, required=True)
468
+ p.add_argument("--ckpt", type=str, required=True)
469
+ p.add_argument("--demographics_csv", type=str, required=True)
470
+ p.add_argument("--perturbation", type=str, required=True, choices=PERTURBATIONS)
471
+ p.add_argument("--level", type=int, required=True, choices=[1, 2, 3, 4, 5])
472
+ p.add_argument("--arch", type=str, default="CLIP:ViT-L/14")
473
+ p.add_argument("--batch_size", type=int, default=8)
474
+ p.add_argument("--loader_workers", type=int, default=4)
475
+ p.add_argument("--gpu", type=int, default=0)
476
+ p.add_argument("--seed", type=int, default=42)
477
+ p.add_argument("--save_json", type=str, default=None)
478
+ return p.parse_args()
479
+
480
+
481
+ def main():
482
+ args = parse_args()
483
+ _set_seed(args.seed)
484
+ device = torch.device(f"cuda:{args.gpu}" if torch.cuda.is_available() else "cpu")
485
+ print(f"[robustness] perturbation={args.perturbation} level={args.level} "
486
+ f"param={SEVERITY[args.perturbation][args.level - 1]} ckpt={args.ckpt}")
487
+
488
+ model = build_model(args.arch)
489
+ load_info = load_ckpt(model, args.ckpt)
490
+ model.to(device).eval()
491
+
492
+ demographics = load_demographics(args.demographics_csv)
493
+
494
+ dataset = PerturbedAVLip(args.real_list_path, args.fake_list_path,
495
+ args.perturbation, args.level, args.seed)
496
+ loader = DataLoader(
497
+ dataset, batch_size=args.batch_size, shuffle=False,
498
+ num_workers=args.loader_workers, pin_memory=torch.cuda.is_available(),
499
+ collate_fn=custom_collate,
500
+ persistent_workers=args.loader_workers > 0,
501
+ prefetch_factor=2 if args.loader_workers > 0 else None,
502
+ )
503
+
504
+ all_scores, all_labels, all_paths = [], [], []
505
+ with torch.inference_mode():
506
+ for imgs, crops, labels, paths in tqdm(
507
+ loader, desc=f"{args.perturbation}/L{args.level}", leave=False):
508
+ imgs = imgs.to(device)
509
+ crops = [[t.to(device) for t in sc] for sc in crops]
510
+ features = model.get_features(imgs).to(device)
511
+ logits = model(crops, features)[0]
512
+ prob = torch.sigmoid(logits.flatten()).cpu().numpy()
513
+ all_scores.extend(prob.tolist())
514
+ all_labels.extend(labels.numpy().tolist())
515
+ all_paths.extend(paths)
516
+
517
+ # ----- clip-level aggregation by basename -----
518
+ bag_scores = collections.defaultdict(list)
519
+ bag_meta = {}
520
+ for path, lab, sc in zip(all_paths, all_labels, all_scores):
521
+ basename = _extract_basename(path)
522
+ bag_scores[basename].append(sc)
523
+ if basename not in bag_meta:
524
+ mid = _extract_model_id(path, lab)
525
+ demo = demographics.get(basename, {"gender": "", "race4": "", "age_group": ""})
526
+ bag_meta[basename] = {"label": int(lab), "model_id": mid, **demo}
527
+
528
+ clip_keys = sorted(bag_scores)
529
+ clip_scores = np.array([float(np.mean(bag_scores[k])) for k in clip_keys])
530
+ clip_labels = np.array([bag_meta[k]["label"] for k in clip_keys])
531
+ clip_models = [bag_meta[k]["model_id"] for k in clip_keys]
532
+ clip_demos = {d: [bag_meta[k][d] for k in clip_keys] for d in DEMO_DIMS}
533
+
534
+ result = {
535
+ "perturbation": args.perturbation,
536
+ "level": args.level,
537
+ "param": SEVERITY[args.perturbation][args.level - 1],
538
+ "n_clips": len(clip_keys),
539
+ "n_samples": len(all_scores),
540
+ }
541
+
542
+ # overall (clip-level)
543
+ o = _metrics_block(clip_labels.tolist(), clip_scores.tolist())
544
+ o["Accuracy"] = o["Accuracy@0.50"]
545
+ result["overall_clip"] = o
546
+
547
+ # per-fake-vs-real (clip-level)
548
+ real_idx = [i for i, y in enumerate(clip_labels) if y == 0]
549
+ real_scores = clip_scores[real_idx].tolist()
550
+ real_labels = clip_labels[real_idx].tolist()
551
+
552
+ fake_models = sorted({m for m, l in zip(clip_models, clip_labels) if l == 1})
553
+ per_fake = {}
554
+ for fm in fake_models:
555
+ idxs = [i for i, (m, l) in enumerate(zip(clip_models, clip_labels))
556
+ if m == fm and l == 1]
557
+ joint_s = clip_scores[idxs].tolist() + real_scores
558
+ joint_l = clip_labels[idxs].tolist() + real_labels
559
+ block = _metrics_block(joint_l, joint_s)
560
+ block["Accuracy"] = block["Accuracy@0.50"]
561
+ per_fake[fm] = block
562
+ result["per_fake_vs_real"] = per_fake
563
+
564
+ # fairness (whole test, clip-level)
565
+ result["fairness_overall"] = {}
566
+ for d in DEMO_DIMS:
567
+ groups = clip_demos[d]
568
+ valid = [i for i, g in enumerate(groups) if g]
569
+ if not valid:
570
+ continue
571
+ fb = compute_fairness(
572
+ [clip_labels[i] for i in valid],
573
+ [clip_scores[i] for i in valid],
574
+ [groups[i] for i in valid],
575
+ )
576
+ result["fairness_overall"][d] = fb
577
+
578
+ # ----- console summary -----
579
+ print(f"\n[{args.perturbation} L{args.level}] overall_clip "
580
+ f"AUROC={_fmt4(o['AUROC'])} AP={_fmt4(o['AP'])} Acc={_fmt4(o['Accuracy'])} "
581
+ f"Acc@EER={_fmt4(o['Acc@EER'])} TPR@1%FPR={_fmt4(o['TPR@FPR=1%'])} "
582
+ f"TPR@0.1%FPR={_fmt4(o['TPR@FPR=0.1%'])} "
583
+ f"(n_clips={result['n_clips']} n_samples={result['n_samples']})")
584
+ for fm, blk in per_fake.items():
585
+ print(f" [{fm}+Real] AUROC={_fmt4(blk['AUROC'])} AP={_fmt4(blk['AP'])} "
586
+ f"Acc={_fmt4(blk['Accuracy'])} Acc@EER={_fmt4(blk['Acc@EER'])}")
587
+ for d in DEMO_DIMS:
588
+ fb = result["fairness_overall"].get(d)
589
+ if fb:
590
+ print(f" fairness[{d}] F_FPR={fb['F_FPR']:.2f} F_MEO={fb['F_MEO']:.2f} "
591
+ f"F_DP={fb['F_DP']:.2f} F_OAE={fb['F_OAE']:.2f}")
592
+
593
+ # ----- save / append json -----
594
+ if args.save_json:
595
+ os.makedirs(os.path.dirname(args.save_json) or ".", exist_ok=True)
596
+ existing = []
597
+ if os.path.exists(args.save_json):
598
+ try:
599
+ with open(args.save_json) as f:
600
+ blob = json.load(f)
601
+ existing = blob.get("runs", []) if isinstance(blob, dict) else []
602
+ except Exception:
603
+ existing = []
604
+ run = {
605
+ "ckpt": args.ckpt,
606
+ "saved_at": time.strftime("%Y-%m-%d %H:%M:%S"),
607
+ "load_info": load_info,
608
+ "real_list_path": args.real_list_path,
609
+ "fake_list_path": args.fake_list_path,
610
+ "demographics_csv": args.demographics_csv,
611
+ "seed": args.seed,
612
+ **result,
613
+ }
614
+ existing.append(run)
615
+ with open(args.save_json, "w") as f:
616
+ json.dump({"runs": existing}, f, indent=2, default=float)
617
+ print(f"\n>>> Appended run to {args.save_json}")
618
+
619
+
620
+ if __name__ == "__main__":
621
+ main()
evaluate_test.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """evaluate_test.py
2
+
3
+ Plain test-set evaluation for LipFD: load a trained ckpt, run inference on
4
+ the FairTalking-Bench test split, and report:
5
+ - overall (clip-level): AUROC / AP / Accuracy / Acc@EER / TPR@1%FPR / TPR@0.1%FPR
6
+ - per-fake-vs-real (each fake model paired with all reals)
7
+ - fairness (gender / race4 / age_group): F_FPR, F_MEO, F_DP, F_OAE
8
+ Clip-level aggregation: mean prob over all frames sharing the same basename
9
+ (e.g. '2358_Real', '1681_Fake').
10
+
11
+ NO perturbation, NO sweeping — single pass over the test set.
12
+
13
+ ============================================================================
14
+ Usage
15
+ ============================================================================
16
+ cd /apdcephfs_gy4/share_303628665/joywu/research/LipFD
17
+ /opt/conda/envs/LipFD/bin/python evaluate_test.py \
18
+ --real_list_path datasets/FairTalking-Bench/test/0_real \
19
+ --fake_list_path datasets/FairTalking-Bench/test/1_fake \
20
+ --ckpt checkpoints/lipfd_train/model_epoch_44.pth \
21
+ --demographics_csv /apdcephfs_gy4/share_303628665/joywu/research/test.csv \
22
+ --batch_size 16 --loader_workers 4 --gpu 0 \
23
+ --save_json robustness/test_clean.json
24
+ """
25
+
26
+ import argparse
27
+ import collections
28
+ import csv as _csv
29
+ import json
30
+ import os
31
+ import sys
32
+ import time
33
+
34
+ import cv2
35
+ import numpy as np
36
+ import torch
37
+ import torchvision.transforms as transforms
38
+ from sklearn.metrics import (
39
+ accuracy_score,
40
+ average_precision_score,
41
+ classification_report,
42
+ confusion_matrix,
43
+ roc_auc_score,
44
+ roc_curve,
45
+ )
46
+ from torch.utils.data import DataLoader, Dataset
47
+ from tqdm import tqdm
48
+
49
+ _REPO_ROOT = os.path.dirname(os.path.abspath(__file__))
50
+ sys.path.insert(0, _REPO_ROOT)
51
+
52
+ from models import build_model # noqa: E402
53
+ import utils as _u # noqa: E402
54
+ from evaluate_robustness import ( # noqa: E402 reuse the helpers
55
+ DEMO_DIMS,
56
+ _extract_basename,
57
+ _extract_model_id,
58
+ _metrics_block,
59
+ _fmt4,
60
+ _set_seed,
61
+ load_ckpt,
62
+ compute_fairness,
63
+ load_demographics,
64
+ custom_collate,
65
+ )
66
+
67
+
68
+ class TestAVLip(Dataset):
69
+ """Mirrors data.AVLip preprocessing; no perturbation."""
70
+
71
+ def __init__(self, real_dir, fake_dir):
72
+ self.real_list = _u.get_list(real_dir)
73
+ self.fake_list = _u.get_list(fake_dir)
74
+ self.label_dict = {p: 0 for p in self.real_list}
75
+ self.label_dict.update({p: 1 for p in self.fake_list})
76
+ self.total_list = self.real_list + self.fake_list
77
+
78
+ def __len__(self):
79
+ return len(self.total_list)
80
+
81
+ def _read_with_skip(self, idx, tried):
82
+ if len(tried) >= len(self.total_list):
83
+ raise RuntimeError("All samples are corrupted or cannot be read!")
84
+ tried.add(idx)
85
+ path = self.total_list[idx]
86
+ if not os.path.exists(path):
87
+ print(f"WARNING: File not found, skipping: {path}")
88
+ return self._read_with_skip((idx + 1) % len(self.total_list), tried)
89
+ img_cv = cv2.imread(path)
90
+ if img_cv is None:
91
+ print(f"WARNING: Failed to read image, skipping: {path}")
92
+ return self._read_with_skip((idx + 1) % len(self.total_list), tried)
93
+ return img_cv, self.label_dict[path], path
94
+
95
+ def __getitem__(self, idx):
96
+ img_cv, label, path = self._read_with_skip(idx, set())
97
+ img = torch.tensor(img_cv, dtype=torch.float32).permute(2, 0, 1)
98
+ # FIX: 5-crop slicing — see evaluate_robustness.py:286 for context.
99
+ crops = [[transforms.Resize((224, 224))(img[:, 500:, i*500:(i+1)*500]) for i in range(5)], [], []]
100
+ crop_idx = [(28, 196), (61, 163)]
101
+ for i in range(len(crops[0])):
102
+ crops[1].append(transforms.Resize((224, 224))(
103
+ crops[0][i][:, crop_idx[0][0]:crop_idx[0][1], crop_idx[0][0]:crop_idx[0][1]]))
104
+ crops[2].append(transforms.Resize((224, 224))(
105
+ crops[0][i][:, crop_idx[1][0]:crop_idx[1][1], crop_idx[1][0]:crop_idx[1][1]]))
106
+ big = transforms.Resize((1120, 1120))(img)
107
+ return big, crops, label, path
108
+
109
+
110
+ def parse_args():
111
+ p = argparse.ArgumentParser()
112
+ p.add_argument("--real_list_path", type=str, required=True)
113
+ p.add_argument("--fake_list_path", type=str, required=True)
114
+ p.add_argument("--ckpt", type=str, required=True)
115
+ p.add_argument("--demographics_csv", type=str, required=True)
116
+ p.add_argument("--arch", type=str, default="CLIP:ViT-L/14")
117
+ p.add_argument("--batch_size", type=int, default=16)
118
+ p.add_argument("--loader_workers", type=int, default=4)
119
+ p.add_argument("--gpu", type=int, default=0)
120
+ p.add_argument("--seed", type=int, default=42)
121
+ p.add_argument("--save_json", type=str, default=None,
122
+ help="Output JSON. Overwrites if exists (single test = single object, not a list).")
123
+ return p.parse_args()
124
+
125
+
126
+ def main():
127
+ args = parse_args()
128
+ _set_seed(args.seed)
129
+ device = torch.device(f"cuda:{args.gpu}" if torch.cuda.is_available() else "cpu")
130
+ print(f"[test] ckpt={args.ckpt}")
131
+
132
+ model = build_model(args.arch)
133
+ load_info = load_ckpt(model, args.ckpt)
134
+ model.to(device).eval()
135
+
136
+ demographics = load_demographics(args.demographics_csv)
137
+
138
+ dataset = TestAVLip(args.real_list_path, args.fake_list_path)
139
+ loader = DataLoader(
140
+ dataset, batch_size=args.batch_size, shuffle=False,
141
+ num_workers=args.loader_workers, pin_memory=torch.cuda.is_available(),
142
+ collate_fn=custom_collate,
143
+ persistent_workers=args.loader_workers > 0,
144
+ prefetch_factor=2 if args.loader_workers > 0 else None,
145
+ )
146
+
147
+ all_scores, all_labels, all_paths = [], [], []
148
+ with torch.inference_mode():
149
+ for imgs, crops, labels, paths in tqdm(loader, desc="test", leave=False):
150
+ imgs = imgs.to(device)
151
+ crops = [[t.to(device) for t in sc] for sc in crops]
152
+ features = model.get_features(imgs).to(device)
153
+ logits = model(crops, features)[0]
154
+ prob = torch.sigmoid(logits.flatten()).cpu().numpy()
155
+ all_scores.extend(prob.tolist())
156
+ all_labels.extend(labels.numpy().tolist())
157
+ all_paths.extend(paths)
158
+
159
+ # ----- clip-level aggregation by basename -----
160
+ bag_scores = collections.defaultdict(list)
161
+ bag_meta = {}
162
+ for path, lab, sc in zip(all_paths, all_labels, all_scores):
163
+ basename = _extract_basename(path)
164
+ bag_scores[basename].append(sc)
165
+ if basename not in bag_meta:
166
+ mid = _extract_model_id(path, lab)
167
+ demo = demographics.get(basename, {"gender": "", "race4": "", "age_group": ""})
168
+ bag_meta[basename] = {"label": int(lab), "model_id": mid, **demo}
169
+
170
+ clip_keys = sorted(bag_scores)
171
+ clip_scores = np.array([float(np.mean(bag_scores[k])) for k in clip_keys])
172
+ clip_labels = np.array([bag_meta[k]["label"] for k in clip_keys])
173
+ clip_models = [bag_meta[k]["model_id"] for k in clip_keys]
174
+ clip_demos = {d: [bag_meta[k][d] for k in clip_keys] for d in DEMO_DIMS}
175
+
176
+ result = {
177
+ "n_clips": len(clip_keys),
178
+ "n_samples": len(all_scores),
179
+ }
180
+
181
+ # overall (clip-level)
182
+ o = _metrics_block(clip_labels.tolist(), clip_scores.tolist())
183
+ o["Accuracy"] = o["Accuracy@0.50"]
184
+ result["overall_clip"] = o
185
+
186
+ # per-fake-vs-real
187
+ real_idx = [i for i, y in enumerate(clip_labels) if y == 0]
188
+ real_scores = clip_scores[real_idx].tolist()
189
+ real_labels = clip_labels[real_idx].tolist()
190
+
191
+ fake_models = sorted({m for m, l in zip(clip_models, clip_labels) if l == 1})
192
+ per_fake = {}
193
+ for fm in fake_models:
194
+ idxs = [i for i, (m, l) in enumerate(zip(clip_models, clip_labels))
195
+ if m == fm and l == 1]
196
+ joint_s = clip_scores[idxs].tolist() + real_scores
197
+ joint_l = clip_labels[idxs].tolist() + real_labels
198
+ block = _metrics_block(joint_l, joint_s)
199
+ block["Accuracy"] = block["Accuracy@0.50"]
200
+ per_fake[fm] = block
201
+ result["per_fake_vs_real"] = per_fake
202
+
203
+ # fairness
204
+ result["fairness_overall"] = {}
205
+ for d in DEMO_DIMS:
206
+ groups = clip_demos[d]
207
+ valid = [i for i, g in enumerate(groups) if g]
208
+ if not valid:
209
+ continue
210
+ fb = compute_fairness(
211
+ [clip_labels[i] for i in valid],
212
+ [clip_scores[i] for i in valid],
213
+ [groups[i] for i in valid],
214
+ )
215
+ result["fairness_overall"][d] = fb
216
+
217
+ # ----- console summary -----
218
+ print(f"\n[test] overall_clip "
219
+ f"AUROC={_fmt4(o['AUROC'])} AP={_fmt4(o['AP'])} Acc={_fmt4(o['Accuracy'])} "
220
+ f"Acc@EER={_fmt4(o['Acc@EER'])} TPR@1%FPR={_fmt4(o['TPR@FPR=1%'])} "
221
+ f"TPR@0.1%FPR={_fmt4(o['TPR@FPR=0.1%'])} "
222
+ f"(n_clips={result['n_clips']} n_samples={result['n_samples']})")
223
+ for fm, blk in per_fake.items():
224
+ print(f" [{fm}+Real] AUROC={_fmt4(blk['AUROC'])} AP={_fmt4(blk['AP'])} "
225
+ f"Acc={_fmt4(blk['Accuracy'])} Acc@EER={_fmt4(blk['Acc@EER'])}")
226
+ for d in DEMO_DIMS:
227
+ fb = result["fairness_overall"].get(d)
228
+ if fb:
229
+ print(f" fairness[{d}] F_FPR={fb['F_FPR']:.2f} F_MEO={fb['F_MEO']:.2f} "
230
+ f"F_DP={fb['F_DP']:.2f} F_OAE={fb['F_OAE']:.2f}")
231
+
232
+ # ----- save json (single test = one object, not a list) -----
233
+ if args.save_json:
234
+ os.makedirs(os.path.dirname(args.save_json) or ".", exist_ok=True)
235
+ run = {
236
+ "ckpt": args.ckpt,
237
+ "saved_at": time.strftime("%Y-%m-%d %H:%M:%S"),
238
+ "load_info": load_info,
239
+ "real_list_path": args.real_list_path,
240
+ "fake_list_path": args.fake_list_path,
241
+ "demographics_csv": args.demographics_csv,
242
+ "seed": args.seed,
243
+ **result,
244
+ }
245
+ with open(args.save_json, "w") as f:
246
+ json.dump(run, f, indent=2, default=float)
247
+ print(f"\n>>> Saved test result to {args.save_json}")
248
+
249
+
250
+ if __name__ == "__main__":
251
+ main()
models/LipFD.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import torch.nn as nn
4
+ from .clip import clip
5
+ from .region_awareness import get_backbone
6
+
7
+
8
+ class LipFD(nn.Module):
9
+ def __init__(self, name, num_classes=1):
10
+ super(LipFD, self).__init__()
11
+
12
+ self.conv1 = nn.Conv2d(
13
+ 3, 3, kernel_size=5, stride=5
14
+ ) # (1120, 1120) -> (224, 224)
15
+ self.encoder, self.preprocess = clip.load(name, device="cpu")
16
+ self.backbone = get_backbone()
17
+
18
+ def forward(self, x, feature):
19
+ return self.backbone(x, feature)
20
+
21
+ def get_features(self, x):
22
+ x = self.conv1(x)
23
+ features = self.encoder.encode_image(x)
24
+ return features
25
+
26
+
27
+ class RALoss(nn.Module):
28
+ def __init__(self):
29
+ super(RALoss, self).__init__()
30
+
31
+ def forward(self, alphas_max, alphas_org):
32
+ loss = 0.0
33
+ batch_size = alphas_org[0].shape[0]
34
+ for i in range(len(alphas_org)):
35
+ loss_wt = 0.0
36
+ for j in range(batch_size):
37
+ loss_wt += torch.Tensor([10]).to(alphas_max[i][j].device) / torch.exp(
38
+ alphas_max[i][j] - alphas_org[i][j]
39
+ )
40
+ loss += loss_wt / batch_size
41
+ return loss
42
+
models/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .clip_models import CLIPModel
2
+ from .LipFD import LipFD, RALoss
3
+
4
+ VALID_NAMES = [
5
+ "CLIP:ViT-B/32",
6
+ "CLIP:ViT-B/16",
7
+ "CLIP:ViT-L/14",
8
+ ]
9
+
10
+
11
+ def get_model(name):
12
+ assert name in VALID_NAMES
13
+ if name.startswith("CLIP:"):
14
+ return CLIPModel(name[5:])
15
+ else:
16
+ assert False
17
+
18
+
19
+ def build_model(transformer_name):
20
+ assert transformer_name in VALID_NAMES
21
+ if transformer_name.startswith("CLIP:"):
22
+ return LipFD(transformer_name[5:])
23
+ else:
24
+ assert False
25
+
26
+
27
+ def get_loss():
28
+ return RALoss()
models/clip_models.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .clip import clip
2
+ from PIL import Image
3
+ import torch.nn as nn
4
+
5
+
6
+ CHANNELS = {
7
+ "RN50" : 1024,
8
+ "ViT-L/14" : 768
9
+ }
10
+
11
+ class CLIPModel(nn.Module):
12
+ def __init__(self, name, num_classes=1):
13
+ super(CLIPModel, self).__init__()
14
+
15
+ self.model, self.preprocess = clip.load(name, device="cpu") # self.preprecess will not be used during training, which is handled in Dataset class
16
+ self.fc = nn.Linear( CHANNELS[name], num_classes )
17
+
18
+
19
+ def forward(self, x, return_feature=False):
20
+ features = self.model.encode_image(x)
21
+ if return_feature:
22
+ return features
23
+ return self.fc(features)
24
+
models/region_awareness.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import Tensor
3
+ import torch.nn as nn
4
+ from typing import Type, Any, Callable, Union, List, Optional
5
+ from torch.nn.functional import softmax
6
+
7
+ try:
8
+ from torch.hub import load_state_dict_from_url
9
+ except ImportError:
10
+ from torch.utils.model_zoo import load_url as load_state_dict_from_url
11
+
12
+ model_urls = {
13
+ 'resnet18': 'https://download.pytorch.org/models/resnet18-f37072fd.pth',
14
+ 'resnet34': 'https://download.pytorch.org/models/resnet34-b627a593.pth',
15
+ 'resnet50': 'https://download.pytorch.org/models/resnet50-0676ba61.pth',
16
+ 'resnet101': 'https://download.pytorch.org/models/resnet101-63fe2227.pth',
17
+ 'resnet152': 'https://download.pytorch.org/models/resnet152-394f9c45.pth',
18
+ 'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
19
+ 'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',
20
+ 'wideget_backbone50_2': 'https://download.pytorch.org/models/wideget_backbone50_2-95faca4d.pth',
21
+ 'wideget_backbone101_2': 'https://download.pytorch.org/models/wideget_backbone101_2-32ee1156.pth',
22
+ }
23
+
24
+
25
+ def conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv2d:
26
+ """3x3 convolution with padding"""
27
+ return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
28
+ padding=dilation, groups=groups, bias=False, dilation=dilation)
29
+
30
+
31
+ def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:
32
+ """1x1 convolution"""
33
+ return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
34
+
35
+
36
+ class BasicBlock(nn.Module):
37
+ expansion: int = 1
38
+
39
+ def __init__(
40
+ self,
41
+ inplanes: int,
42
+ planes: int,
43
+ stride: int = 1,
44
+ downsample: Optional[nn.Module] = None,
45
+ groups: int = 1,
46
+ base_width: int = 64,
47
+ dilation: int = 1,
48
+ norm_layer: Optional[Callable[..., nn.Module]] = None
49
+ ) -> None:
50
+ super(BasicBlock, self).__init__()
51
+ if norm_layer is None:
52
+ norm_layer = nn.BatchNorm2d
53
+ if groups != 1 or base_width != 64:
54
+ raise ValueError('BasicBlock only supports groups=1 and base_width=64')
55
+ if dilation > 1:
56
+ raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
57
+ # Both self.conv1 and self.downsample layers downsample the input when stride != 1
58
+ self.conv1 = conv3x3(inplanes, planes, stride)
59
+ self.bn1 = norm_layer(planes)
60
+ self.relu = nn.ReLU(inplace=True)
61
+ self.conv2 = conv3x3(planes, planes)
62
+ self.bn2 = norm_layer(planes)
63
+ self.downsample = downsample
64
+ self.stride = stride
65
+
66
+ def forward(self, x: Tensor) -> Tensor:
67
+ identity = x
68
+
69
+ out = self.conv1(x)
70
+ out = self.bn1(out)
71
+ out = self.relu(out)
72
+
73
+ out = self.conv2(out)
74
+ out = self.bn2(out)
75
+
76
+ if self.downsample is not None:
77
+ identity = self.downsample(x)
78
+
79
+ out += identity
80
+ out = self.relu(out)
81
+
82
+ return out
83
+
84
+
85
+ class Bottleneck(nn.Module):
86
+ expansion: int = 4
87
+
88
+ def __init__(
89
+ self,
90
+ inplanes: int,
91
+ planes: int,
92
+ stride: int = 1,
93
+ downsample: Optional[nn.Module] = None,
94
+ groups: int = 1,
95
+ base_width: int = 64,
96
+ dilation: int = 1,
97
+ norm_layer: Optional[Callable[..., nn.Module]] = None
98
+ ) -> None:
99
+ super(Bottleneck, self).__init__()
100
+ if norm_layer is None:
101
+ norm_layer = nn.BatchNorm2d
102
+ width = int(planes * (base_width / 64.)) * groups
103
+ # Both self.conv2 and self.downsample layers downsample the input when stride != 1
104
+ self.conv1 = conv1x1(inplanes, width)
105
+ self.bn1 = norm_layer(width)
106
+ self.conv2 = conv3x3(width, width, stride, groups, dilation)
107
+ self.bn2 = norm_layer(width)
108
+ self.conv3 = conv1x1(width, planes * self.expansion)
109
+ self.bn3 = norm_layer(planes * self.expansion)
110
+ self.relu = nn.ReLU(inplace=True)
111
+ self.downsample = downsample
112
+ self.stride = stride
113
+
114
+ def forward(self, x: Tensor) -> Tensor:
115
+ identity = x
116
+
117
+ out = self.conv1(x)
118
+ out = self.bn1(out)
119
+ out = self.relu(out)
120
+
121
+ out = self.conv2(out)
122
+ out = self.bn2(out)
123
+ out = self.relu(out)
124
+
125
+ out = self.conv3(out)
126
+ out = self.bn3(out)
127
+
128
+ if self.downsample is not None:
129
+ identity = self.downsample(x)
130
+
131
+ out += identity
132
+ out = self.relu(out)
133
+
134
+ return out
135
+
136
+
137
+ class ResNet(nn.Module):
138
+
139
+ def __init__(
140
+ self,
141
+ block: Type[Union[BasicBlock, Bottleneck]],
142
+ layers: List[int],
143
+ num_classes: int = 1000,
144
+ zero_init_residual: bool = False,
145
+ groups: int = 1,
146
+ width_per_group: int = 64,
147
+ replace_stride_with_dilation: Optional[List[bool]] = None,
148
+ norm_layer: Optional[Callable[..., nn.Module]] = None
149
+ ) -> None:
150
+ super(ResNet, self).__init__()
151
+ if norm_layer is None:
152
+ norm_layer = nn.BatchNorm2d
153
+ self._norm_layer = norm_layer
154
+
155
+ self.inplanes = 64
156
+ self.dilation = 1
157
+ if replace_stride_with_dilation is None:
158
+ # each element in the tuple indicates if we should replace
159
+ # the 2x2 stride with a dilated convolution instead
160
+ replace_stride_with_dilation = [False, False, False]
161
+ if len(replace_stride_with_dilation) != 3:
162
+ raise ValueError("replace_stride_with_dilation should be None "
163
+ "or a 3-element tuple, got {}".format(replace_stride_with_dilation))
164
+ self.groups = groups
165
+ self.base_width = width_per_group
166
+ self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
167
+ bias=False)
168
+ self.bn1 = norm_layer(self.inplanes)
169
+ self.relu = nn.ReLU(inplace=True)
170
+ self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
171
+ self.layer1 = self._make_layer(block, 64, layers[0])
172
+ self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
173
+ dilate=replace_stride_with_dilation[0])
174
+ self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
175
+ dilate=replace_stride_with_dilation[1])
176
+ self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
177
+ dilate=replace_stride_with_dilation[2])
178
+ self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
179
+ self.get_weight = nn.Sequential(
180
+ nn.Linear(512 * block.expansion + 768, 1), # TODO: 768 is the length of global feature
181
+ nn.Sigmoid()
182
+ )
183
+ self.fc = nn.Linear(512 * block.expansion + 768, 1)
184
+
185
+ for m in self.modules():
186
+ if isinstance(m, nn.Conv2d):
187
+ nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
188
+ elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
189
+ nn.init.constant_(m.weight, 1)
190
+ nn.init.constant_(m.bias, 0)
191
+
192
+ # Zero-initialize the last BN in each residual branch,
193
+ # so that the residual branch starts with zeros, and each residual block behaves like an identity.
194
+ # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
195
+ if zero_init_residual:
196
+ for m in self.modules():
197
+ if isinstance(m, Bottleneck):
198
+ nn.init.constant_(m.bn3.weight, 0) # type: ignore[arg-type]
199
+ elif isinstance(m, BasicBlock):
200
+ nn.init.constant_(m.bn2.weight, 0) # type: ignore[arg-type]
201
+
202
+ def _make_layer(self, block: Type[Union[BasicBlock, Bottleneck]], planes: int, blocks: int,
203
+ stride: int = 1, dilate: bool = False) -> nn.Sequential:
204
+ norm_layer = self._norm_layer
205
+ downsample = None
206
+ previous_dilation = self.dilation
207
+ if dilate:
208
+ self.dilation *= stride
209
+ stride = 1
210
+ if stride != 1 or self.inplanes != planes * block.expansion:
211
+ downsample = nn.Sequential(
212
+ conv1x1(self.inplanes, planes * block.expansion, stride),
213
+ norm_layer(planes * block.expansion),
214
+ )
215
+
216
+ layers = []
217
+ layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
218
+ self.base_width, previous_dilation, norm_layer))
219
+ self.inplanes = planes * block.expansion
220
+ for _ in range(1, blocks):
221
+ layers.append(block(self.inplanes, planes, groups=self.groups,
222
+ base_width=self.base_width, dilation=self.dilation,
223
+ norm_layer=norm_layer))
224
+
225
+ return nn.Sequential(*layers)
226
+
227
+ def _forward_impl(self, x, feature):
228
+ # The comment resolution is based on input size is 224*224 imagenet
229
+ # f.shape: (batch_size, 3, 224, 224), feature.shape: (batch_size, 768)
230
+ features, weights, parts, weights_org, weights_max = [list() for i in range(5)]
231
+ for i in range(len(x[0])):
232
+ features.clear()
233
+ weights.clear()
234
+ for j in range(len(x)):
235
+ f = x[j][i]
236
+ f = self.conv1(f)
237
+ f = self.bn1(f)
238
+ f = self.relu(f)
239
+ f = self.maxpool(f)
240
+ f = self.layer1(f)
241
+ f = self.layer2(f)
242
+ f = self.layer3(f)
243
+ f = self.layer4(f)
244
+ f = self.avgpool(f)
245
+ f = torch.flatten(f, 1)
246
+
247
+ # features.append(f)
248
+ features.append(torch.cat([f, feature], dim=1)) # concat regional feature with global feature
249
+ weights.append(self.get_weight(features[-1]))
250
+
251
+ features_stack = torch.stack(features, dim=2)
252
+ weights_stack = torch.stack(weights, dim=2)
253
+ weights_stack = softmax(weights_stack, dim=2)
254
+
255
+ weights_max.append(weights_stack[:, :, :len(x)].max(dim=2)[0])
256
+ weights_org.append(weights_stack[:, :, 0])
257
+ parts.append(features_stack.mul(weights_stack).sum(2).div(weights_stack.sum(2)))
258
+ parts_stack = torch.stack(parts, dim=0)
259
+ out = parts_stack.sum(0).div(parts_stack.shape[0])
260
+
261
+ pred_score = self.fc(out)
262
+
263
+ return pred_score, weights_max, weights_org
264
+
265
+ def forward(self, x, feature):
266
+ return self._forward_impl(x, feature)
267
+
268
+
269
+ def _get_backbone(
270
+ arch: str,
271
+ block: Type[Union[BasicBlock, Bottleneck]],
272
+ layers: List[int],
273
+ pretrained: bool,
274
+ progress: bool,
275
+ **kwargs: Any
276
+ ) -> ResNet:
277
+ model = ResNet(block, layers, num_classes=1, **kwargs)
278
+ if pretrained:
279
+ state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)
280
+ model.load_state_dict(state_dict)
281
+ return model
282
+
283
+
284
+ def get_backbone(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
285
+ r"""ResNet-50 model from
286
+ `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.
287
+
288
+ Args:
289
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
290
+ progress (bool): If True, displays a progress bar of the download to stderr
291
+ """
292
+ return _get_backbone('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress, **kwargs)
293
+
294
+
295
+ if __name__ == '__main__':
296
+ model = get_backbone()
297
+ data = [[] for i in range(3)]
298
+ for i in range(3):
299
+ for j in range(5):
300
+ data[i].append(torch.rand((10, 3, 224, 224)))
301
+ feature = torch.rand((10, 768))
302
+ pred_score, weights_max, weights_org = model(data, feature)
303
+ pass
models/resnet.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import Tensor
3
+ import torch.nn as nn
4
+ from typing import Type, Any, Callable, Union, List, Optional
5
+
6
+ try:
7
+ from torch.hub import load_state_dict_from_url
8
+ except ImportError:
9
+ from torch.utils.model_zoo import load_url as load_state_dict_from_url
10
+
11
+
12
+ model_urls = {
13
+ 'resnet18': 'https://download.pytorch.org/models/resnet18-f37072fd.pth',
14
+ 'resnet34': 'https://download.pytorch.org/models/resnet34-b627a593.pth',
15
+ 'resnet50': 'https://download.pytorch.org/models/resnet50-0676ba61.pth',
16
+ 'resnet101': 'https://download.pytorch.org/models/resnet101-63fe2227.pth',
17
+ 'resnet152': 'https://download.pytorch.org/models/resnet152-394f9c45.pth',
18
+ 'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
19
+ 'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',
20
+ 'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',
21
+ 'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',
22
+ }
23
+
24
+
25
+
26
+
27
+ def conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv2d:
28
+ """3x3 convolution with padding"""
29
+ return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
30
+ padding=dilation, groups=groups, bias=False, dilation=dilation)
31
+
32
+
33
+ def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:
34
+ """1x1 convolution"""
35
+ return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
36
+
37
+
38
+ class BasicBlock(nn.Module):
39
+ expansion: int = 1
40
+
41
+ def __init__(
42
+ self,
43
+ inplanes: int,
44
+ planes: int,
45
+ stride: int = 1,
46
+ downsample: Optional[nn.Module] = None,
47
+ groups: int = 1,
48
+ base_width: int = 64,
49
+ dilation: int = 1,
50
+ norm_layer: Optional[Callable[..., nn.Module]] = None
51
+ ) -> None:
52
+ super(BasicBlock, self).__init__()
53
+ if norm_layer is None:
54
+ norm_layer = nn.BatchNorm2d
55
+ if groups != 1 or base_width != 64:
56
+ raise ValueError('BasicBlock only supports groups=1 and base_width=64')
57
+ if dilation > 1:
58
+ raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
59
+ # Both self.conv1 and self.downsample layers downsample the input when stride != 1
60
+ self.conv1 = conv3x3(inplanes, planes, stride)
61
+ self.bn1 = norm_layer(planes)
62
+ self.relu = nn.ReLU(inplace=True)
63
+ self.conv2 = conv3x3(planes, planes)
64
+ self.bn2 = norm_layer(planes)
65
+ self.downsample = downsample
66
+ self.stride = stride
67
+
68
+ def forward(self, x: Tensor) -> Tensor:
69
+ identity = x
70
+
71
+ out = self.conv1(x)
72
+ out = self.bn1(out)
73
+ out = self.relu(out)
74
+
75
+ out = self.conv2(out)
76
+ out = self.bn2(out)
77
+
78
+ if self.downsample is not None:
79
+ identity = self.downsample(x)
80
+
81
+ out += identity
82
+ out = self.relu(out)
83
+
84
+ return out
85
+
86
+
87
+ class Bottleneck(nn.Module):
88
+ # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)
89
+ # while original implementation places the stride at the first 1x1 convolution(self.conv1)
90
+ # according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385.
91
+ # This variant is also known as ResNet V1.5 and improves accuracy according to
92
+ # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch.
93
+
94
+ expansion: int = 4
95
+
96
+ def __init__(
97
+ self,
98
+ inplanes: int,
99
+ planes: int,
100
+ stride: int = 1,
101
+ downsample: Optional[nn.Module] = None,
102
+ groups: int = 1,
103
+ base_width: int = 64,
104
+ dilation: int = 1,
105
+ norm_layer: Optional[Callable[..., nn.Module]] = None
106
+ ) -> None:
107
+ super(Bottleneck, self).__init__()
108
+ if norm_layer is None:
109
+ norm_layer = nn.BatchNorm2d
110
+ width = int(planes * (base_width / 64.)) * groups
111
+ # Both self.conv2 and self.downsample layers downsample the input when stride != 1
112
+ self.conv1 = conv1x1(inplanes, width)
113
+ self.bn1 = norm_layer(width)
114
+ self.conv2 = conv3x3(width, width, stride, groups, dilation)
115
+ self.bn2 = norm_layer(width)
116
+ self.conv3 = conv1x1(width, planes * self.expansion)
117
+ self.bn3 = norm_layer(planes * self.expansion)
118
+ self.relu = nn.ReLU(inplace=True)
119
+ self.downsample = downsample
120
+ self.stride = stride
121
+
122
+ def forward(self, x: Tensor) -> Tensor:
123
+ identity = x
124
+
125
+ out = self.conv1(x)
126
+ out = self.bn1(out)
127
+ out = self.relu(out)
128
+
129
+ out = self.conv2(out)
130
+ out = self.bn2(out)
131
+ out = self.relu(out)
132
+
133
+ out = self.conv3(out)
134
+ out = self.bn3(out)
135
+
136
+ if self.downsample is not None:
137
+ identity = self.downsample(x)
138
+
139
+ out += identity
140
+ out = self.relu(out)
141
+
142
+ return out
143
+
144
+
145
+ class ResNet(nn.Module):
146
+
147
+ def __init__(
148
+ self,
149
+ block: Type[Union[BasicBlock, Bottleneck]],
150
+ layers: List[int],
151
+ num_classes: int = 1000,
152
+ zero_init_residual: bool = False,
153
+ groups: int = 1,
154
+ width_per_group: int = 64,
155
+ replace_stride_with_dilation: Optional[List[bool]] = None,
156
+ norm_layer: Optional[Callable[..., nn.Module]] = None
157
+ ) -> None:
158
+ super(ResNet, self).__init__()
159
+ if norm_layer is None:
160
+ norm_layer = nn.BatchNorm2d
161
+ self._norm_layer = norm_layer
162
+
163
+ self.inplanes = 64
164
+ self.dilation = 1
165
+ if replace_stride_with_dilation is None:
166
+ # each element in the tuple indicates if we should replace
167
+ # the 2x2 stride with a dilated convolution instead
168
+ replace_stride_with_dilation = [False, False, False]
169
+ if len(replace_stride_with_dilation) != 3:
170
+ raise ValueError("replace_stride_with_dilation should be None "
171
+ "or a 3-element tuple, got {}".format(replace_stride_with_dilation))
172
+ self.groups = groups
173
+ self.base_width = width_per_group
174
+ self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
175
+ bias=False)
176
+ self.bn1 = norm_layer(self.inplanes)
177
+ self.relu = nn.ReLU(inplace=True)
178
+ self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
179
+ self.layer1 = self._make_layer(block, 64, layers[0])
180
+ self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
181
+ dilate=replace_stride_with_dilation[0])
182
+ self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
183
+ dilate=replace_stride_with_dilation[1])
184
+ self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
185
+ dilate=replace_stride_with_dilation[2])
186
+ self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
187
+ self.fc = nn.Linear(512 * block.expansion, num_classes)
188
+
189
+ for m in self.modules():
190
+ if isinstance(m, nn.Conv2d):
191
+ nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
192
+ elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
193
+ nn.init.constant_(m.weight, 1)
194
+ nn.init.constant_(m.bias, 0)
195
+
196
+ # Zero-initialize the last BN in each residual branch,
197
+ # so that the residual branch starts with zeros, and each residual block behaves like an identity.
198
+ # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
199
+ if zero_init_residual:
200
+ for m in self.modules():
201
+ if isinstance(m, Bottleneck):
202
+ nn.init.constant_(m.bn3.weight, 0) # type: ignore[arg-type]
203
+ elif isinstance(m, BasicBlock):
204
+ nn.init.constant_(m.bn2.weight, 0) # type: ignore[arg-type]
205
+
206
+ def _make_layer(self, block: Type[Union[BasicBlock, Bottleneck]], planes: int, blocks: int,
207
+ stride: int = 1, dilate: bool = False) -> nn.Sequential:
208
+ norm_layer = self._norm_layer
209
+ downsample = None
210
+ previous_dilation = self.dilation
211
+ if dilate:
212
+ self.dilation *= stride
213
+ stride = 1
214
+ if stride != 1 or self.inplanes != planes * block.expansion:
215
+ downsample = nn.Sequential(
216
+ conv1x1(self.inplanes, planes * block.expansion, stride),
217
+ norm_layer(planes * block.expansion),
218
+ )
219
+
220
+ layers = []
221
+ layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
222
+ self.base_width, previous_dilation, norm_layer))
223
+ self.inplanes = planes * block.expansion
224
+ for _ in range(1, blocks):
225
+ layers.append(block(self.inplanes, planes, groups=self.groups,
226
+ base_width=self.base_width, dilation=self.dilation,
227
+ norm_layer=norm_layer))
228
+
229
+ return nn.Sequential(*layers)
230
+
231
+ def _forward_impl(self, x):
232
+ # The comment resolution is based on input size is 224*224 imagenet
233
+ out = {}
234
+ x = self.conv1(x)
235
+ x = self.bn1(x)
236
+ x = self.relu(x)
237
+ x = self.maxpool(x)
238
+ out['f0'] = x # N*64*56*56
239
+
240
+ x = self.layer1(x)
241
+ out['f1'] = x # N*64*56*56
242
+
243
+ x = self.layer2(x)
244
+ out['f2'] = x # N*128*28*28
245
+
246
+ x = self.layer3(x)
247
+ out['f3'] = x # N*256*14*14
248
+
249
+ x = self.layer4(x)
250
+ out['f4'] = x # N*512*7*7
251
+
252
+ x = self.avgpool(x)
253
+ x = torch.flatten(x, 1)
254
+ out['penultimate'] = x # N*512
255
+
256
+ x = self.fc(x)
257
+ out['logits'] = x # N*1000
258
+
259
+ # return all features
260
+ return out
261
+
262
+ # return final classification result
263
+ # return x
264
+
265
+ def forward(self, x):
266
+ return self._forward_impl(x)
267
+
268
+
269
+ def _resnet(
270
+ arch: str,
271
+ block: Type[Union[BasicBlock, Bottleneck]],
272
+ layers: List[int],
273
+ pretrained: bool,
274
+ progress: bool,
275
+ **kwargs: Any
276
+ ) -> ResNet:
277
+ model = ResNet(block, layers, **kwargs)
278
+ if pretrained:
279
+ state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)
280
+ model.load_state_dict(state_dict)
281
+ return model
282
+
283
+
284
+ def resnet18(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
285
+ r"""ResNet-18 model from
286
+ `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.
287
+
288
+ Args:
289
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
290
+ progress (bool): If True, displays a progress bar of the download to stderr
291
+ """
292
+ return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress, **kwargs)
293
+
294
+
295
+ def resnet34(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
296
+ r"""ResNet-34 model from
297
+ `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.
298
+
299
+ Args:
300
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
301
+ progress (bool): If True, displays a progress bar of the download to stderr
302
+ """
303
+ return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress, **kwargs)
304
+
305
+
306
+ def resnet50(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
307
+ r"""ResNet-50 model from
308
+ `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.
309
+
310
+ Args:
311
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
312
+ progress (bool): If True, displays a progress bar of the download to stderr
313
+ """
314
+ return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress, **kwargs)
315
+
316
+
317
+ def resnet101(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
318
+ r"""ResNet-101 model from
319
+ `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.
320
+
321
+ Args:
322
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
323
+ progress (bool): If True, displays a progress bar of the download to stderr
324
+ """
325
+ return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress, **kwargs)
326
+
327
+
328
+ def resnet152(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:
329
+ r"""ResNet-152 model from
330
+ `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_.
331
+
332
+ Args:
333
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
334
+ progress (bool): If True, displays a progress bar of the download to stderr
335
+ """
336
+ return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress, **kwargs)
models/vision_transformer.py ADDED
@@ -0,0 +1,481 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from collections import OrderedDict
3
+ from functools import partial
4
+ from typing import Any, Callable, List, NamedTuple, Optional
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+
9
+ # from .._internally_replaced_utils import load_state_dict_from_url
10
+ from .vision_transformer_misc import ConvNormActivation
11
+ from .vision_transformer_utils import _log_api_usage_once
12
+
13
+ try:
14
+ from torch.hub import load_state_dict_from_url
15
+ except ImportError:
16
+ from torch.utils.model_zoo import load_url as load_state_dict_from_url
17
+
18
+ # __all__ = [
19
+ # "VisionTransformer",
20
+ # "vit_b_16",
21
+ # "vit_b_32",
22
+ # "vit_l_16",
23
+ # "vit_l_32",
24
+ # ]
25
+
26
+ model_urls = {
27
+ "vit_b_16": "https://download.pytorch.org/models/vit_b_16-c867db91.pth",
28
+ "vit_b_32": "https://download.pytorch.org/models/vit_b_32-d86f8d99.pth",
29
+ "vit_l_16": "https://download.pytorch.org/models/vit_l_16-852ce7e3.pth",
30
+ "vit_l_32": "https://download.pytorch.org/models/vit_l_32-c7638314.pth",
31
+ }
32
+
33
+
34
+ class ConvStemConfig(NamedTuple):
35
+ out_channels: int
36
+ kernel_size: int
37
+ stride: int
38
+ norm_layer: Callable[..., nn.Module] = nn.BatchNorm2d
39
+ activation_layer: Callable[..., nn.Module] = nn.ReLU
40
+
41
+
42
+ class MLPBlock(nn.Sequential):
43
+ """Transformer MLP block."""
44
+
45
+ def __init__(self, in_dim: int, mlp_dim: int, dropout: float):
46
+ super().__init__()
47
+ self.linear_1 = nn.Linear(in_dim, mlp_dim)
48
+ self.act = nn.GELU()
49
+ self.dropout_1 = nn.Dropout(dropout)
50
+ self.linear_2 = nn.Linear(mlp_dim, in_dim)
51
+ self.dropout_2 = nn.Dropout(dropout)
52
+
53
+ nn.init.xavier_uniform_(self.linear_1.weight)
54
+ nn.init.xavier_uniform_(self.linear_2.weight)
55
+ nn.init.normal_(self.linear_1.bias, std=1e-6)
56
+ nn.init.normal_(self.linear_2.bias, std=1e-6)
57
+
58
+
59
+ class EncoderBlock(nn.Module):
60
+ """Transformer encoder block."""
61
+
62
+ def __init__(
63
+ self,
64
+ num_heads: int,
65
+ hidden_dim: int,
66
+ mlp_dim: int,
67
+ dropout: float,
68
+ attention_dropout: float,
69
+ norm_layer: Callable[..., torch.nn.Module] = partial(nn.LayerNorm, eps=1e-6),
70
+ ):
71
+ super().__init__()
72
+ self.num_heads = num_heads
73
+
74
+ # Attention block
75
+ self.ln_1 = norm_layer(hidden_dim)
76
+ self.self_attention = nn.MultiheadAttention(hidden_dim, num_heads, dropout=attention_dropout, batch_first=True)
77
+ self.dropout = nn.Dropout(dropout)
78
+
79
+ # MLP block
80
+ self.ln_2 = norm_layer(hidden_dim)
81
+ self.mlp = MLPBlock(hidden_dim, mlp_dim, dropout)
82
+
83
+ def forward(self, input: torch.Tensor):
84
+ torch._assert(input.dim() == 3, f"Expected (seq_length, batch_size, hidden_dim) got {input.shape}")
85
+ x = self.ln_1(input)
86
+ x, _ = self.self_attention(query=x, key=x, value=x, need_weights=False)
87
+ x = self.dropout(x)
88
+ x = x + input
89
+
90
+ y = self.ln_2(x)
91
+ y = self.mlp(y)
92
+ return x + y
93
+
94
+
95
+ class Encoder(nn.Module):
96
+ """Transformer Model Encoder for sequence to sequence translation."""
97
+
98
+ def __init__(
99
+ self,
100
+ seq_length: int,
101
+ num_layers: int,
102
+ num_heads: int,
103
+ hidden_dim: int,
104
+ mlp_dim: int,
105
+ dropout: float,
106
+ attention_dropout: float,
107
+ norm_layer: Callable[..., torch.nn.Module] = partial(nn.LayerNorm, eps=1e-6),
108
+ ):
109
+ super().__init__()
110
+ # Note that batch_size is on the first dim because
111
+ # we have batch_first=True in nn.MultiAttention() by default
112
+ self.pos_embedding = nn.Parameter(torch.empty(1, seq_length, hidden_dim).normal_(std=0.02)) # from BERT
113
+ self.dropout = nn.Dropout(dropout)
114
+ layers: OrderedDict[str, nn.Module] = OrderedDict()
115
+ for i in range(num_layers):
116
+ layers[f"encoder_layer_{i}"] = EncoderBlock(
117
+ num_heads,
118
+ hidden_dim,
119
+ mlp_dim,
120
+ dropout,
121
+ attention_dropout,
122
+ norm_layer,
123
+ )
124
+ self.layers = nn.Sequential(layers)
125
+ self.ln = norm_layer(hidden_dim)
126
+
127
+ def forward(self, input: torch.Tensor):
128
+ torch._assert(input.dim() == 3, f"Expected (batch_size, seq_length, hidden_dim) got {input.shape}")
129
+ input = input + self.pos_embedding
130
+ return self.ln(self.layers(self.dropout(input)))
131
+
132
+
133
+ class VisionTransformer(nn.Module):
134
+ """Vision Transformer as per https://arxiv.org/abs/2010.11929."""
135
+
136
+ def __init__(
137
+ self,
138
+ image_size: int,
139
+ patch_size: int,
140
+ num_layers: int,
141
+ num_heads: int,
142
+ hidden_dim: int,
143
+ mlp_dim: int,
144
+ dropout: float = 0.0,
145
+ attention_dropout: float = 0.0,
146
+ num_classes: int = 1000,
147
+ representation_size: Optional[int] = None,
148
+ norm_layer: Callable[..., torch.nn.Module] = partial(nn.LayerNorm, eps=1e-6),
149
+ conv_stem_configs: Optional[List[ConvStemConfig]] = None,
150
+ ):
151
+ super().__init__()
152
+ _log_api_usage_once(self)
153
+ torch._assert(image_size % patch_size == 0, "Input shape indivisible by patch size!")
154
+ self.image_size = image_size
155
+ self.patch_size = patch_size
156
+ self.hidden_dim = hidden_dim
157
+ self.mlp_dim = mlp_dim
158
+ self.attention_dropout = attention_dropout
159
+ self.dropout = dropout
160
+ self.num_classes = num_classes
161
+ self.representation_size = representation_size
162
+ self.norm_layer = norm_layer
163
+
164
+ if conv_stem_configs is not None:
165
+ # As per https://arxiv.org/abs/2106.14881
166
+ seq_proj = nn.Sequential()
167
+ prev_channels = 3
168
+ for i, conv_stem_layer_config in enumerate(conv_stem_configs):
169
+ seq_proj.add_module(
170
+ f"conv_bn_relu_{i}",
171
+ ConvNormActivation(
172
+ in_channels=prev_channels,
173
+ out_channels=conv_stem_layer_config.out_channels,
174
+ kernel_size=conv_stem_layer_config.kernel_size,
175
+ stride=conv_stem_layer_config.stride,
176
+ norm_layer=conv_stem_layer_config.norm_layer,
177
+ activation_layer=conv_stem_layer_config.activation_layer,
178
+ ),
179
+ )
180
+ prev_channels = conv_stem_layer_config.out_channels
181
+ seq_proj.add_module(
182
+ "conv_last", nn.Conv2d(in_channels=prev_channels, out_channels=hidden_dim, kernel_size=1)
183
+ )
184
+ self.conv_proj: nn.Module = seq_proj
185
+ else:
186
+ self.conv_proj = nn.Conv2d(
187
+ in_channels=3, out_channels=hidden_dim, kernel_size=patch_size, stride=patch_size
188
+ )
189
+
190
+ seq_length = (image_size // patch_size) ** 2
191
+
192
+ # Add a class token
193
+ self.class_token = nn.Parameter(torch.zeros(1, 1, hidden_dim))
194
+ seq_length += 1
195
+
196
+ self.encoder = Encoder(
197
+ seq_length,
198
+ num_layers,
199
+ num_heads,
200
+ hidden_dim,
201
+ mlp_dim,
202
+ dropout,
203
+ attention_dropout,
204
+ norm_layer,
205
+ )
206
+ self.seq_length = seq_length
207
+
208
+ heads_layers: OrderedDict[str, nn.Module] = OrderedDict()
209
+ if representation_size is None:
210
+ heads_layers["head"] = nn.Linear(hidden_dim, num_classes)
211
+ else:
212
+ heads_layers["pre_logits"] = nn.Linear(hidden_dim, representation_size)
213
+ heads_layers["act"] = nn.Tanh()
214
+ heads_layers["head"] = nn.Linear(representation_size, num_classes)
215
+
216
+ self.heads = nn.Sequential(heads_layers)
217
+
218
+ if isinstance(self.conv_proj, nn.Conv2d):
219
+ # Init the patchify stem
220
+ fan_in = self.conv_proj.in_channels * self.conv_proj.kernel_size[0] * self.conv_proj.kernel_size[1]
221
+ nn.init.trunc_normal_(self.conv_proj.weight, std=math.sqrt(1 / fan_in))
222
+ if self.conv_proj.bias is not None:
223
+ nn.init.zeros_(self.conv_proj.bias)
224
+ elif self.conv_proj.conv_last is not None and isinstance(self.conv_proj.conv_last, nn.Conv2d):
225
+ # Init the last 1x1 conv of the conv stem
226
+ nn.init.normal_(
227
+ self.conv_proj.conv_last.weight, mean=0.0, std=math.sqrt(2.0 / self.conv_proj.conv_last.out_channels)
228
+ )
229
+ if self.conv_proj.conv_last.bias is not None:
230
+ nn.init.zeros_(self.conv_proj.conv_last.bias)
231
+
232
+ if hasattr(self.heads, "pre_logits") and isinstance(self.heads.pre_logits, nn.Linear):
233
+ fan_in = self.heads.pre_logits.in_features
234
+ nn.init.trunc_normal_(self.heads.pre_logits.weight, std=math.sqrt(1 / fan_in))
235
+ nn.init.zeros_(self.heads.pre_logits.bias)
236
+
237
+ if isinstance(self.heads.head, nn.Linear):
238
+ nn.init.zeros_(self.heads.head.weight)
239
+ nn.init.zeros_(self.heads.head.bias)
240
+
241
+ def _process_input(self, x: torch.Tensor) -> torch.Tensor:
242
+ n, c, h, w = x.shape
243
+ p = self.patch_size
244
+ torch._assert(h == self.image_size, "Wrong image height!")
245
+ torch._assert(w == self.image_size, "Wrong image width!")
246
+ n_h = h // p
247
+ n_w = w // p
248
+
249
+ # (n, c, h, w) -> (n, hidden_dim, n_h, n_w)
250
+ x = self.conv_proj(x)
251
+ # (n, hidden_dim, n_h, n_w) -> (n, hidden_dim, (n_h * n_w))
252
+ x = x.reshape(n, self.hidden_dim, n_h * n_w)
253
+
254
+ # (n, hidden_dim, (n_h * n_w)) -> (n, (n_h * n_w), hidden_dim)
255
+ # The self attention layer expects inputs in the format (N, S, E)
256
+ # where S is the source sequence length, N is the batch size, E is the
257
+ # embedding dimension
258
+ x = x.permute(0, 2, 1)
259
+
260
+ return x
261
+
262
+ def forward(self, x: torch.Tensor):
263
+ out = {}
264
+
265
+ # Reshape and permute the input tensor
266
+ x = self._process_input(x)
267
+ n = x.shape[0]
268
+
269
+ # Expand the class token to the full batch
270
+ batch_class_token = self.class_token.expand(n, -1, -1)
271
+ x = torch.cat([batch_class_token, x], dim=1)
272
+
273
+
274
+ x = self.encoder(x)
275
+ img_feature = x[:,1:]
276
+ H = W = int(self.image_size / self.patch_size)
277
+ out['f4'] = img_feature.view(n, H, W, self.hidden_dim).permute(0,3,1,2)
278
+
279
+ # Classifier "token" as used by standard language architectures
280
+ x = x[:, 0]
281
+ out['penultimate'] = x
282
+
283
+ x = self.heads(x) # I checked that for all pretrained ViT, this is just a fc
284
+ out['logits'] = x
285
+
286
+ return out
287
+
288
+
289
+ def _vision_transformer(
290
+ arch: str,
291
+ patch_size: int,
292
+ num_layers: int,
293
+ num_heads: int,
294
+ hidden_dim: int,
295
+ mlp_dim: int,
296
+ pretrained: bool,
297
+ progress: bool,
298
+ **kwargs: Any,
299
+ ) -> VisionTransformer:
300
+ image_size = kwargs.pop("image_size", 224)
301
+
302
+ model = VisionTransformer(
303
+ image_size=image_size,
304
+ patch_size=patch_size,
305
+ num_layers=num_layers,
306
+ num_heads=num_heads,
307
+ hidden_dim=hidden_dim,
308
+ mlp_dim=mlp_dim,
309
+ **kwargs,
310
+ )
311
+
312
+ if pretrained:
313
+ if arch not in model_urls:
314
+ raise ValueError(f"No checkpoint is available for model type '{arch}'!")
315
+ state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)
316
+ model.load_state_dict(state_dict)
317
+
318
+ return model
319
+
320
+
321
+ def vit_b_16(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VisionTransformer:
322
+ """
323
+ Constructs a vit_b_16 architecture from
324
+ `"An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale" <https://arxiv.org/abs/2010.11929>`_.
325
+
326
+ Args:
327
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
328
+ progress (bool): If True, displays a progress bar of the download to stderr
329
+ """
330
+ return _vision_transformer(
331
+ arch="vit_b_16",
332
+ patch_size=16,
333
+ num_layers=12,
334
+ num_heads=12,
335
+ hidden_dim=768,
336
+ mlp_dim=3072,
337
+ pretrained=pretrained,
338
+ progress=progress,
339
+ **kwargs,
340
+ )
341
+
342
+
343
+ def vit_b_32(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VisionTransformer:
344
+ """
345
+ Constructs a vit_b_32 architecture from
346
+ `"An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale" <https://arxiv.org/abs/2010.11929>`_.
347
+
348
+ Args:
349
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
350
+ progress (bool): If True, displays a progress bar of the download to stderr
351
+ """
352
+ return _vision_transformer(
353
+ arch="vit_b_32",
354
+ patch_size=32,
355
+ num_layers=12,
356
+ num_heads=12,
357
+ hidden_dim=768,
358
+ mlp_dim=3072,
359
+ pretrained=pretrained,
360
+ progress=progress,
361
+ **kwargs,
362
+ )
363
+
364
+
365
+ def vit_l_16(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VisionTransformer:
366
+ """
367
+ Constructs a vit_l_16 architecture from
368
+ `"An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale" <https://arxiv.org/abs/2010.11929>`_.
369
+
370
+ Args:
371
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
372
+ progress (bool): If True, displays a progress bar of the download to stderr
373
+ """
374
+ return _vision_transformer(
375
+ arch="vit_l_16",
376
+ patch_size=16,
377
+ num_layers=24,
378
+ num_heads=16,
379
+ hidden_dim=1024,
380
+ mlp_dim=4096,
381
+ pretrained=pretrained,
382
+ progress=progress,
383
+ **kwargs,
384
+ )
385
+
386
+
387
+ def vit_l_32(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> VisionTransformer:
388
+ """
389
+ Constructs a vit_l_32 architecture from
390
+ `"An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale" <https://arxiv.org/abs/2010.11929>`_.
391
+
392
+ Args:
393
+ pretrained (bool): If True, returns a model pre-trained on ImageNet
394
+ progress (bool): If True, displays a progress bar of the download to stderr
395
+ """
396
+ return _vision_transformer(
397
+ arch="vit_l_32",
398
+ patch_size=32,
399
+ num_layers=24,
400
+ num_heads=16,
401
+ hidden_dim=1024,
402
+ mlp_dim=4096,
403
+ pretrained=pretrained,
404
+ progress=progress,
405
+ **kwargs,
406
+ )
407
+
408
+
409
+ def interpolate_embeddings(
410
+ image_size: int,
411
+ patch_size: int,
412
+ model_state: "OrderedDict[str, torch.Tensor]",
413
+ interpolation_mode: str = "bicubic",
414
+ reset_heads: bool = False,
415
+ ) -> "OrderedDict[str, torch.Tensor]":
416
+ """This function helps interpolating positional embeddings during checkpoint loading,
417
+ especially when you want to apply a pre-trained model on images with different resolution.
418
+
419
+ Args:
420
+ image_size (int): Image size of the new model.
421
+ patch_size (int): Patch size of the new model.
422
+ model_state (OrderedDict[str, torch.Tensor]): State dict of the pre-trained model.
423
+ interpolation_mode (str): The algorithm used for upsampling. Default: bicubic.
424
+ reset_heads (bool): If true, not copying the state of heads. Default: False.
425
+
426
+ Returns:
427
+ OrderedDict[str, torch.Tensor]: A state dict which can be loaded into the new model.
428
+ """
429
+ # Shape of pos_embedding is (1, seq_length, hidden_dim)
430
+ pos_embedding = model_state["encoder.pos_embedding"]
431
+ n, seq_length, hidden_dim = pos_embedding.shape
432
+ if n != 1:
433
+ raise ValueError(f"Unexpected position embedding shape: {pos_embedding.shape}")
434
+
435
+ new_seq_length = (image_size // patch_size) ** 2 + 1
436
+
437
+ # Need to interpolate the weights for the position embedding.
438
+ # We do this by reshaping the positions embeddings to a 2d grid, performing
439
+ # an interpolation in the (h, w) space and then reshaping back to a 1d grid.
440
+ if new_seq_length != seq_length:
441
+ # The class token embedding shouldn't be interpolated so we split it up.
442
+ seq_length -= 1
443
+ new_seq_length -= 1
444
+ pos_embedding_token = pos_embedding[:, :1, :]
445
+ pos_embedding_img = pos_embedding[:, 1:, :]
446
+
447
+ # (1, seq_length, hidden_dim) -> (1, hidden_dim, seq_length)
448
+ pos_embedding_img = pos_embedding_img.permute(0, 2, 1)
449
+ seq_length_1d = int(math.sqrt(seq_length))
450
+ torch._assert(seq_length_1d * seq_length_1d == seq_length, "seq_length is not a perfect square!")
451
+
452
+ # (1, hidden_dim, seq_length) -> (1, hidden_dim, seq_l_1d, seq_l_1d)
453
+ pos_embedding_img = pos_embedding_img.reshape(1, hidden_dim, seq_length_1d, seq_length_1d)
454
+ new_seq_length_1d = image_size // patch_size
455
+
456
+ # Perform interpolation.
457
+ # (1, hidden_dim, seq_l_1d, seq_l_1d) -> (1, hidden_dim, new_seq_l_1d, new_seq_l_1d)
458
+ new_pos_embedding_img = nn.functional.interpolate(
459
+ pos_embedding_img,
460
+ size=new_seq_length_1d,
461
+ mode=interpolation_mode,
462
+ align_corners=True,
463
+ )
464
+
465
+ # (1, hidden_dim, new_seq_l_1d, new_seq_l_1d) -> (1, hidden_dim, new_seq_length)
466
+ new_pos_embedding_img = new_pos_embedding_img.reshape(1, hidden_dim, new_seq_length)
467
+
468
+ # (1, hidden_dim, new_seq_length) -> (1, new_seq_length, hidden_dim)
469
+ new_pos_embedding_img = new_pos_embedding_img.permute(0, 2, 1)
470
+ new_pos_embedding = torch.cat([pos_embedding_token, new_pos_embedding_img], dim=1)
471
+
472
+ model_state["encoder.pos_embedding"] = new_pos_embedding
473
+
474
+ if reset_heads:
475
+ model_state_copy: "OrderedDict[str, torch.Tensor]" = OrderedDict()
476
+ for k, v in model_state.items():
477
+ if not k.startswith("heads"):
478
+ model_state_copy[k] = v
479
+ model_state = model_state_copy
480
+
481
+ return model_state
models/vision_transformer_misc.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, List, Optional
2
+
3
+ import torch
4
+ from torch import Tensor
5
+
6
+ from .vision_transformer_utils import _log_api_usage_once
7
+
8
+
9
+ interpolate = torch.nn.functional.interpolate
10
+
11
+
12
+ # This is not in nn
13
+ class FrozenBatchNorm2d(torch.nn.Module):
14
+ """
15
+ BatchNorm2d where the batch statistics and the affine parameters are fixed
16
+
17
+ Args:
18
+ num_features (int): Number of features ``C`` from an expected input of size ``(N, C, H, W)``
19
+ eps (float): a value added to the denominator for numerical stability. Default: 1e-5
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ num_features: int,
25
+ eps: float = 1e-5,
26
+ ):
27
+ super().__init__()
28
+ _log_api_usage_once(self)
29
+ self.eps = eps
30
+ self.register_buffer("weight", torch.ones(num_features))
31
+ self.register_buffer("bias", torch.zeros(num_features))
32
+ self.register_buffer("running_mean", torch.zeros(num_features))
33
+ self.register_buffer("running_var", torch.ones(num_features))
34
+
35
+ def _load_from_state_dict(
36
+ self,
37
+ state_dict: dict,
38
+ prefix: str,
39
+ local_metadata: dict,
40
+ strict: bool,
41
+ missing_keys: List[str],
42
+ unexpected_keys: List[str],
43
+ error_msgs: List[str],
44
+ ):
45
+ num_batches_tracked_key = prefix + "num_batches_tracked"
46
+ if num_batches_tracked_key in state_dict:
47
+ del state_dict[num_batches_tracked_key]
48
+
49
+ super()._load_from_state_dict(
50
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
51
+ )
52
+
53
+ def forward(self, x: Tensor) -> Tensor:
54
+ # move reshapes to the beginning
55
+ # to make it fuser-friendly
56
+ w = self.weight.reshape(1, -1, 1, 1)
57
+ b = self.bias.reshape(1, -1, 1, 1)
58
+ rv = self.running_var.reshape(1, -1, 1, 1)
59
+ rm = self.running_mean.reshape(1, -1, 1, 1)
60
+ scale = w * (rv + self.eps).rsqrt()
61
+ bias = b - rm * scale
62
+ return x * scale + bias
63
+
64
+ def __repr__(self) -> str:
65
+ return f"{self.__class__.__name__}({self.weight.shape[0]}, eps={self.eps})"
66
+
67
+
68
+ class ConvNormActivation(torch.nn.Sequential):
69
+ """
70
+ Configurable block used for Convolution-Normalzation-Activation blocks.
71
+
72
+ Args:
73
+ in_channels (int): Number of channels in the input image
74
+ out_channels (int): Number of channels produced by the Convolution-Normalzation-Activation block
75
+ kernel_size: (int, optional): Size of the convolving kernel. Default: 3
76
+ stride (int, optional): Stride of the convolution. Default: 1
77
+ padding (int, tuple or str, optional): Padding added to all four sides of the input. Default: None, in wich case it will calculated as ``padding = (kernel_size - 1) // 2 * dilation``
78
+ groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1
79
+ norm_layer (Callable[..., torch.nn.Module], optional): Norm layer that will be stacked on top of the convolutiuon layer. If ``None`` this layer wont be used. Default: ``torch.nn.BatchNorm2d``
80
+ activation_layer (Callable[..., torch.nn.Module], optinal): Activation function which will be stacked on top of the normalization layer (if not None), otherwise on top of the conv layer. If ``None`` this layer wont be used. Default: ``torch.nn.ReLU``
81
+ dilation (int): Spacing between kernel elements. Default: 1
82
+ inplace (bool): Parameter for the activation layer, which can optionally do the operation in-place. Default ``True``
83
+ bias (bool, optional): Whether to use bias in the convolution layer. By default, biases are included if ``norm_layer is None``.
84
+
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ in_channels: int,
90
+ out_channels: int,
91
+ kernel_size: int = 3,
92
+ stride: int = 1,
93
+ padding: Optional[int] = None,
94
+ groups: int = 1,
95
+ norm_layer: Optional[Callable[..., torch.nn.Module]] = torch.nn.BatchNorm2d,
96
+ activation_layer: Optional[Callable[..., torch.nn.Module]] = torch.nn.ReLU,
97
+ dilation: int = 1,
98
+ inplace: Optional[bool] = True,
99
+ bias: Optional[bool] = None,
100
+ ) -> None:
101
+ if padding is None:
102
+ padding = (kernel_size - 1) // 2 * dilation
103
+ if bias is None:
104
+ bias = norm_layer is None
105
+ layers = [
106
+ torch.nn.Conv2d(
107
+ in_channels,
108
+ out_channels,
109
+ kernel_size,
110
+ stride,
111
+ padding,
112
+ dilation=dilation,
113
+ groups=groups,
114
+ bias=bias,
115
+ )
116
+ ]
117
+ if norm_layer is not None:
118
+ layers.append(norm_layer(out_channels))
119
+ if activation_layer is not None:
120
+ params = {} if inplace is None else {"inplace": inplace}
121
+ layers.append(activation_layer(**params))
122
+ super().__init__(*layers)
123
+ _log_api_usage_once(self)
124
+ self.out_channels = out_channels
125
+
126
+
127
+ class SqueezeExcitation(torch.nn.Module):
128
+ """
129
+ This block implements the Squeeze-and-Excitation block from https://arxiv.org/abs/1709.01507 (see Fig. 1).
130
+ Parameters ``activation``, and ``scale_activation`` correspond to ``delta`` and ``sigma`` in in eq. 3.
131
+
132
+ Args:
133
+ input_channels (int): Number of channels in the input image
134
+ squeeze_channels (int): Number of squeeze channels
135
+ activation (Callable[..., torch.nn.Module], optional): ``delta`` activation. Default: ``torch.nn.ReLU``
136
+ scale_activation (Callable[..., torch.nn.Module]): ``sigma`` activation. Default: ``torch.nn.Sigmoid``
137
+ """
138
+
139
+ def __init__(
140
+ self,
141
+ input_channels: int,
142
+ squeeze_channels: int,
143
+ activation: Callable[..., torch.nn.Module] = torch.nn.ReLU,
144
+ scale_activation: Callable[..., torch.nn.Module] = torch.nn.Sigmoid,
145
+ ) -> None:
146
+ super().__init__()
147
+ _log_api_usage_once(self)
148
+ self.avgpool = torch.nn.AdaptiveAvgPool2d(1)
149
+ self.fc1 = torch.nn.Conv2d(input_channels, squeeze_channels, 1)
150
+ self.fc2 = torch.nn.Conv2d(squeeze_channels, input_channels, 1)
151
+ self.activation = activation()
152
+ self.scale_activation = scale_activation()
153
+
154
+ def _scale(self, input: Tensor) -> Tensor:
155
+ scale = self.avgpool(input)
156
+ scale = self.fc1(scale)
157
+ scale = self.activation(scale)
158
+ scale = self.fc2(scale)
159
+ return self.scale_activation(scale)
160
+
161
+ def forward(self, input: Tensor) -> Tensor:
162
+ scale = self._scale(input)
163
+ return scale * input
models/vision_transformer_utils.py ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import pathlib
3
+ import warnings
4
+ from types import FunctionType
5
+ from typing import Any, BinaryIO, List, Optional, Tuple, Union
6
+
7
+ import numpy as np
8
+ import torch
9
+ from PIL import Image, ImageColor, ImageDraw, ImageFont
10
+
11
+ __all__ = [
12
+ "make_grid",
13
+ "save_image",
14
+ "draw_bounding_boxes",
15
+ "draw_segmentation_masks",
16
+ "draw_keypoints",
17
+ "flow_to_image",
18
+ ]
19
+
20
+
21
+ @torch.no_grad()
22
+ def make_grid(
23
+ tensor: Union[torch.Tensor, List[torch.Tensor]],
24
+ nrow: int = 8,
25
+ padding: int = 2,
26
+ normalize: bool = False,
27
+ value_range: Optional[Tuple[int, int]] = None,
28
+ scale_each: bool = False,
29
+ pad_value: float = 0.0,
30
+ **kwargs,
31
+ ) -> torch.Tensor:
32
+ """
33
+ Make a grid of images.
34
+
35
+ Args:
36
+ tensor (Tensor or list): 4D mini-batch Tensor of shape (B x C x H x W)
37
+ or a list of images all of the same size.
38
+ nrow (int, optional): Number of images displayed in each row of the grid.
39
+ The final grid size is ``(B / nrow, nrow)``. Default: ``8``.
40
+ padding (int, optional): amount of padding. Default: ``2``.
41
+ normalize (bool, optional): If True, shift the image to the range (0, 1),
42
+ by the min and max values specified by ``value_range``. Default: ``False``.
43
+ value_range (tuple, optional): tuple (min, max) where min and max are numbers,
44
+ then these numbers are used to normalize the image. By default, min and max
45
+ are computed from the tensor.
46
+ range (tuple. optional):
47
+ .. warning::
48
+ This parameter was deprecated in ``0.12`` and will be removed in ``0.14``. Please use ``value_range``
49
+ instead.
50
+ scale_each (bool, optional): If ``True``, scale each image in the batch of
51
+ images separately rather than the (min, max) over all images. Default: ``False``.
52
+ pad_value (float, optional): Value for the padded pixels. Default: ``0``.
53
+
54
+ Returns:
55
+ grid (Tensor): the tensor containing grid of images.
56
+ """
57
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
58
+ _log_api_usage_once(make_grid)
59
+ if not (torch.is_tensor(tensor) or (isinstance(tensor, list) and all(torch.is_tensor(t) for t in tensor))):
60
+ raise TypeError(f"tensor or list of tensors expected, got {type(tensor)}")
61
+
62
+ if "range" in kwargs.keys():
63
+ warnings.warn(
64
+ "The parameter 'range' is deprecated since 0.12 and will be removed in 0.14. "
65
+ "Please use 'value_range' instead."
66
+ )
67
+ value_range = kwargs["range"]
68
+
69
+ # if list of tensors, convert to a 4D mini-batch Tensor
70
+ if isinstance(tensor, list):
71
+ tensor = torch.stack(tensor, dim=0)
72
+
73
+ if tensor.dim() == 2: # single image H x W
74
+ tensor = tensor.unsqueeze(0)
75
+ if tensor.dim() == 3: # single image
76
+ if tensor.size(0) == 1: # if single-channel, convert to 3-channel
77
+ tensor = torch.cat((tensor, tensor, tensor), 0)
78
+ tensor = tensor.unsqueeze(0)
79
+
80
+ if tensor.dim() == 4 and tensor.size(1) == 1: # single-channel images
81
+ tensor = torch.cat((tensor, tensor, tensor), 1)
82
+
83
+ if normalize is True:
84
+ tensor = tensor.clone() # avoid modifying tensor in-place
85
+ if value_range is not None:
86
+ assert isinstance(
87
+ value_range, tuple
88
+ ), "value_range has to be a tuple (min, max) if specified. min and max are numbers"
89
+
90
+ def norm_ip(img, low, high):
91
+ img.clamp_(min=low, max=high)
92
+ img.sub_(low).div_(max(high - low, 1e-5))
93
+
94
+ def norm_range(t, value_range):
95
+ if value_range is not None:
96
+ norm_ip(t, value_range[0], value_range[1])
97
+ else:
98
+ norm_ip(t, float(t.min()), float(t.max()))
99
+
100
+ if scale_each is True:
101
+ for t in tensor: # loop over mini-batch dimension
102
+ norm_range(t, value_range)
103
+ else:
104
+ norm_range(tensor, value_range)
105
+
106
+ assert isinstance(tensor, torch.Tensor)
107
+ if tensor.size(0) == 1:
108
+ return tensor.squeeze(0)
109
+
110
+ # make the mini-batch of images into a grid
111
+ nmaps = tensor.size(0)
112
+ xmaps = min(nrow, nmaps)
113
+ ymaps = int(math.ceil(float(nmaps) / xmaps))
114
+ height, width = int(tensor.size(2) + padding), int(tensor.size(3) + padding)
115
+ num_channels = tensor.size(1)
116
+ grid = tensor.new_full((num_channels, height * ymaps + padding, width * xmaps + padding), pad_value)
117
+ k = 0
118
+ for y in range(ymaps):
119
+ for x in range(xmaps):
120
+ if k >= nmaps:
121
+ break
122
+ # Tensor.copy_() is a valid method but seems to be missing from the stubs
123
+ # https://pytorch.org/docs/stable/tensors.html#torch.Tensor.copy_
124
+ grid.narrow(1, y * height + padding, height - padding).narrow( # type: ignore[attr-defined]
125
+ 2, x * width + padding, width - padding
126
+ ).copy_(tensor[k])
127
+ k = k + 1
128
+ return grid
129
+
130
+
131
+ @torch.no_grad()
132
+ def save_image(
133
+ tensor: Union[torch.Tensor, List[torch.Tensor]],
134
+ fp: Union[str, pathlib.Path, BinaryIO],
135
+ format: Optional[str] = None,
136
+ **kwargs,
137
+ ) -> None:
138
+ """
139
+ Save a given Tensor into an image file.
140
+
141
+ Args:
142
+ tensor (Tensor or list): Image to be saved. If given a mini-batch tensor,
143
+ saves the tensor as a grid of images by calling ``make_grid``.
144
+ fp (string or file object): A filename or a file object
145
+ format(Optional): If omitted, the format to use is determined from the filename extension.
146
+ If a file object was used instead of a filename, this parameter should always be used.
147
+ **kwargs: Other arguments are documented in ``make_grid``.
148
+ """
149
+
150
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
151
+ _log_api_usage_once(save_image)
152
+ grid = make_grid(tensor, **kwargs)
153
+ # Add 0.5 after unnormalizing to [0, 255] to round to nearest integer
154
+ ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", torch.uint8).numpy()
155
+ im = Image.fromarray(ndarr)
156
+ im.save(fp, format=format)
157
+
158
+
159
+ @torch.no_grad()
160
+ def draw_bounding_boxes(
161
+ image: torch.Tensor,
162
+ boxes: torch.Tensor,
163
+ labels: Optional[List[str]] = None,
164
+ colors: Optional[Union[List[Union[str, Tuple[int, int, int]]], str, Tuple[int, int, int]]] = None,
165
+ fill: Optional[bool] = False,
166
+ width: int = 1,
167
+ font: Optional[str] = None,
168
+ font_size: int = 10,
169
+ ) -> torch.Tensor:
170
+
171
+ """
172
+ Draws bounding boxes on given image.
173
+ The values of the input image should be uint8 between 0 and 255.
174
+ If fill is True, Resulting Tensor should be saved as PNG image.
175
+
176
+ Args:
177
+ image (Tensor): Tensor of shape (C x H x W) and dtype uint8.
178
+ boxes (Tensor): Tensor of size (N, 4) containing bounding boxes in (xmin, ymin, xmax, ymax) format. Note that
179
+ the boxes are absolute coordinates with respect to the image. In other words: `0 <= xmin < xmax < W` and
180
+ `0 <= ymin < ymax < H`.
181
+ labels (List[str]): List containing the labels of bounding boxes.
182
+ colors (color or list of colors, optional): List containing the colors
183
+ of the boxes or single color for all boxes. The color can be represented as
184
+ PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``.
185
+ By default, random colors are generated for boxes.
186
+ fill (bool): If `True` fills the bounding box with specified color.
187
+ width (int): Width of bounding box.
188
+ font (str): A filename containing a TrueType font. If the file is not found in this filename, the loader may
189
+ also search in other directories, such as the `fonts/` directory on Windows or `/Library/Fonts/`,
190
+ `/System/Library/Fonts/` and `~/Library/Fonts/` on macOS.
191
+ font_size (int): The requested font size in points.
192
+
193
+ Returns:
194
+ img (Tensor[C, H, W]): Image Tensor of dtype uint8 with bounding boxes plotted.
195
+ """
196
+
197
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
198
+ _log_api_usage_once(draw_bounding_boxes)
199
+ if not isinstance(image, torch.Tensor):
200
+ raise TypeError(f"Tensor expected, got {type(image)}")
201
+ elif image.dtype != torch.uint8:
202
+ raise ValueError(f"Tensor uint8 expected, got {image.dtype}")
203
+ elif image.dim() != 3:
204
+ raise ValueError("Pass individual images, not batches")
205
+ elif image.size(0) not in {1, 3}:
206
+ raise ValueError("Only grayscale and RGB images are supported")
207
+
208
+ num_boxes = boxes.shape[0]
209
+
210
+ if labels is None:
211
+ labels: Union[List[str], List[None]] = [None] * num_boxes # type: ignore[no-redef]
212
+ elif len(labels) != num_boxes:
213
+ raise ValueError(
214
+ f"Number of boxes ({num_boxes}) and labels ({len(labels)}) mismatch. Please specify labels for each box."
215
+ )
216
+
217
+ if colors is None:
218
+ colors = _generate_color_palette(num_boxes)
219
+ elif isinstance(colors, list):
220
+ if len(colors) < num_boxes:
221
+ raise ValueError(f"Number of colors ({len(colors)}) is less than number of boxes ({num_boxes}). ")
222
+ else: # colors specifies a single color for all boxes
223
+ colors = [colors] * num_boxes
224
+
225
+ colors = [(ImageColor.getrgb(color) if isinstance(color, str) else color) for color in colors]
226
+
227
+ # Handle Grayscale images
228
+ if image.size(0) == 1:
229
+ image = torch.tile(image, (3, 1, 1))
230
+
231
+ ndarr = image.permute(1, 2, 0).cpu().numpy()
232
+ img_to_draw = Image.fromarray(ndarr)
233
+ img_boxes = boxes.to(torch.int64).tolist()
234
+
235
+ if fill:
236
+ draw = ImageDraw.Draw(img_to_draw, "RGBA")
237
+ else:
238
+ draw = ImageDraw.Draw(img_to_draw)
239
+
240
+ txt_font = ImageFont.load_default() if font is None else ImageFont.truetype(font=font, size=font_size)
241
+
242
+ for bbox, color, label in zip(img_boxes, colors, labels): # type: ignore[arg-type]
243
+ if fill:
244
+ fill_color = color + (100,)
245
+ draw.rectangle(bbox, width=width, outline=color, fill=fill_color)
246
+ else:
247
+ draw.rectangle(bbox, width=width, outline=color)
248
+
249
+ if label is not None:
250
+ margin = width + 1
251
+ draw.text((bbox[0] + margin, bbox[1] + margin), label, fill=color, font=txt_font)
252
+
253
+ return torch.from_numpy(np.array(img_to_draw)).permute(2, 0, 1).to(dtype=torch.uint8)
254
+
255
+
256
+ @torch.no_grad()
257
+ def draw_segmentation_masks(
258
+ image: torch.Tensor,
259
+ masks: torch.Tensor,
260
+ alpha: float = 0.8,
261
+ colors: Optional[Union[List[Union[str, Tuple[int, int, int]]], str, Tuple[int, int, int]]] = None,
262
+ ) -> torch.Tensor:
263
+
264
+ """
265
+ Draws segmentation masks on given RGB image.
266
+ The values of the input image should be uint8 between 0 and 255.
267
+
268
+ Args:
269
+ image (Tensor): Tensor of shape (3, H, W) and dtype uint8.
270
+ masks (Tensor): Tensor of shape (num_masks, H, W) or (H, W) and dtype bool.
271
+ alpha (float): Float number between 0 and 1 denoting the transparency of the masks.
272
+ 0 means full transparency, 1 means no transparency.
273
+ colors (color or list of colors, optional): List containing the colors
274
+ of the masks or single color for all masks. The color can be represented as
275
+ PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``.
276
+ By default, random colors are generated for each mask.
277
+
278
+ Returns:
279
+ img (Tensor[C, H, W]): Image Tensor, with segmentation masks drawn on top.
280
+ """
281
+
282
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
283
+ _log_api_usage_once(draw_segmentation_masks)
284
+ if not isinstance(image, torch.Tensor):
285
+ raise TypeError(f"The image must be a tensor, got {type(image)}")
286
+ elif image.dtype != torch.uint8:
287
+ raise ValueError(f"The image dtype must be uint8, got {image.dtype}")
288
+ elif image.dim() != 3:
289
+ raise ValueError("Pass individual images, not batches")
290
+ elif image.size()[0] != 3:
291
+ raise ValueError("Pass an RGB image. Other Image formats are not supported")
292
+ if masks.ndim == 2:
293
+ masks = masks[None, :, :]
294
+ if masks.ndim != 3:
295
+ raise ValueError("masks must be of shape (H, W) or (batch_size, H, W)")
296
+ if masks.dtype != torch.bool:
297
+ raise ValueError(f"The masks must be of dtype bool. Got {masks.dtype}")
298
+ if masks.shape[-2:] != image.shape[-2:]:
299
+ raise ValueError("The image and the masks must have the same height and width")
300
+
301
+ num_masks = masks.size()[0]
302
+ if colors is not None and num_masks > len(colors):
303
+ raise ValueError(f"There are more masks ({num_masks}) than colors ({len(colors)})")
304
+
305
+ if colors is None:
306
+ colors = _generate_color_palette(num_masks)
307
+
308
+ if not isinstance(colors, list):
309
+ colors = [colors]
310
+ if not isinstance(colors[0], (tuple, str)):
311
+ raise ValueError("colors must be a tuple or a string, or a list thereof")
312
+ if isinstance(colors[0], tuple) and len(colors[0]) != 3:
313
+ raise ValueError("It seems that you passed a tuple of colors instead of a list of colors")
314
+
315
+ out_dtype = torch.uint8
316
+
317
+ colors_ = []
318
+ for color in colors:
319
+ if isinstance(color, str):
320
+ color = ImageColor.getrgb(color)
321
+ colors_.append(torch.tensor(color, dtype=out_dtype))
322
+
323
+ img_to_draw = image.detach().clone()
324
+ # TODO: There might be a way to vectorize this
325
+ for mask, color in zip(masks, colors_):
326
+ img_to_draw[:, mask] = color[:, None]
327
+
328
+ out = image * (1 - alpha) + img_to_draw * alpha
329
+ return out.to(out_dtype)
330
+
331
+
332
+ @torch.no_grad()
333
+ def draw_keypoints(
334
+ image: torch.Tensor,
335
+ keypoints: torch.Tensor,
336
+ connectivity: Optional[List[Tuple[int, int]]] = None,
337
+ colors: Optional[Union[str, Tuple[int, int, int]]] = None,
338
+ radius: int = 2,
339
+ width: int = 3,
340
+ ) -> torch.Tensor:
341
+
342
+ """
343
+ Draws Keypoints on given RGB image.
344
+ The values of the input image should be uint8 between 0 and 255.
345
+
346
+ Args:
347
+ image (Tensor): Tensor of shape (3, H, W) and dtype uint8.
348
+ keypoints (Tensor): Tensor of shape (num_instances, K, 2) the K keypoints location for each of the N instances,
349
+ in the format [x, y].
350
+ connectivity (List[Tuple[int, int]]]): A List of tuple where,
351
+ each tuple contains pair of keypoints to be connected.
352
+ colors (str, Tuple): The color can be represented as
353
+ PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``.
354
+ radius (int): Integer denoting radius of keypoint.
355
+ width (int): Integer denoting width of line connecting keypoints.
356
+
357
+ Returns:
358
+ img (Tensor[C, H, W]): Image Tensor of dtype uint8 with keypoints drawn.
359
+ """
360
+
361
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
362
+ _log_api_usage_once(draw_keypoints)
363
+ if not isinstance(image, torch.Tensor):
364
+ raise TypeError(f"The image must be a tensor, got {type(image)}")
365
+ elif image.dtype != torch.uint8:
366
+ raise ValueError(f"The image dtype must be uint8, got {image.dtype}")
367
+ elif image.dim() != 3:
368
+ raise ValueError("Pass individual images, not batches")
369
+ elif image.size()[0] != 3:
370
+ raise ValueError("Pass an RGB image. Other Image formats are not supported")
371
+
372
+ if keypoints.ndim != 3:
373
+ raise ValueError("keypoints must be of shape (num_instances, K, 2)")
374
+
375
+ ndarr = image.permute(1, 2, 0).cpu().numpy()
376
+ img_to_draw = Image.fromarray(ndarr)
377
+ draw = ImageDraw.Draw(img_to_draw)
378
+ img_kpts = keypoints.to(torch.int64).tolist()
379
+
380
+ for kpt_id, kpt_inst in enumerate(img_kpts):
381
+ for inst_id, kpt in enumerate(kpt_inst):
382
+ x1 = kpt[0] - radius
383
+ x2 = kpt[0] + radius
384
+ y1 = kpt[1] - radius
385
+ y2 = kpt[1] + radius
386
+ draw.ellipse([x1, y1, x2, y2], fill=colors, outline=None, width=0)
387
+
388
+ if connectivity:
389
+ for connection in connectivity:
390
+ start_pt_x = kpt_inst[connection[0]][0]
391
+ start_pt_y = kpt_inst[connection[0]][1]
392
+
393
+ end_pt_x = kpt_inst[connection[1]][0]
394
+ end_pt_y = kpt_inst[connection[1]][1]
395
+
396
+ draw.line(
397
+ ((start_pt_x, start_pt_y), (end_pt_x, end_pt_y)),
398
+ width=width,
399
+ )
400
+
401
+ return torch.from_numpy(np.array(img_to_draw)).permute(2, 0, 1).to(dtype=torch.uint8)
402
+
403
+
404
+ # Flow visualization code adapted from https://github.com/tomrunia/OpticalFlow_Visualization
405
+ @torch.no_grad()
406
+ def flow_to_image(flow: torch.Tensor) -> torch.Tensor:
407
+
408
+ """
409
+ Converts a flow to an RGB image.
410
+
411
+ Args:
412
+ flow (Tensor): Flow of shape (N, 2, H, W) or (2, H, W) and dtype torch.float.
413
+
414
+ Returns:
415
+ img (Tensor): Image Tensor of dtype uint8 where each color corresponds
416
+ to a given flow direction. Shape is (N, 3, H, W) or (3, H, W) depending on the input.
417
+ """
418
+
419
+ if flow.dtype != torch.float:
420
+ raise ValueError(f"Flow should be of dtype torch.float, got {flow.dtype}.")
421
+
422
+ orig_shape = flow.shape
423
+ if flow.ndim == 3:
424
+ flow = flow[None] # Add batch dim
425
+
426
+ if flow.ndim != 4 or flow.shape[1] != 2:
427
+ raise ValueError(f"Input flow should have shape (2, H, W) or (N, 2, H, W), got {orig_shape}.")
428
+
429
+ max_norm = torch.sum(flow ** 2, dim=1).sqrt().max()
430
+ epsilon = torch.finfo((flow).dtype).eps
431
+ normalized_flow = flow / (max_norm + epsilon)
432
+ img = _normalized_flow_to_image(normalized_flow)
433
+
434
+ if len(orig_shape) == 3:
435
+ img = img[0] # Remove batch dim
436
+ return img
437
+
438
+
439
+ @torch.no_grad()
440
+ def _normalized_flow_to_image(normalized_flow: torch.Tensor) -> torch.Tensor:
441
+
442
+ """
443
+ Converts a batch of normalized flow to an RGB image.
444
+
445
+ Args:
446
+ normalized_flow (torch.Tensor): Normalized flow tensor of shape (N, 2, H, W)
447
+ Returns:
448
+ img (Tensor(N, 3, H, W)): Flow visualization image of dtype uint8.
449
+ """
450
+
451
+ N, _, H, W = normalized_flow.shape
452
+ device = normalized_flow.device
453
+ flow_image = torch.zeros((N, 3, H, W), dtype=torch.uint8, device=device)
454
+ colorwheel = _make_colorwheel().to(device) # shape [55x3]
455
+ num_cols = colorwheel.shape[0]
456
+ norm = torch.sum(normalized_flow ** 2, dim=1).sqrt()
457
+ a = torch.atan2(-normalized_flow[:, 1, :, :], -normalized_flow[:, 0, :, :]) / torch.pi
458
+ fk = (a + 1) / 2 * (num_cols - 1)
459
+ k0 = torch.floor(fk).to(torch.long)
460
+ k1 = k0 + 1
461
+ k1[k1 == num_cols] = 0
462
+ f = fk - k0
463
+
464
+ for c in range(colorwheel.shape[1]):
465
+ tmp = colorwheel[:, c]
466
+ col0 = tmp[k0] / 255.0
467
+ col1 = tmp[k1] / 255.0
468
+ col = (1 - f) * col0 + f * col1
469
+ col = 1 - norm * (1 - col)
470
+ flow_image[:, c, :, :] = torch.floor(255 * col)
471
+ return flow_image
472
+
473
+
474
+ def _make_colorwheel() -> torch.Tensor:
475
+ """
476
+ Generates a color wheel for optical flow visualization as presented in:
477
+ Baker et al. "A Database and Evaluation Methodology for Optical Flow" (ICCV, 2007)
478
+ URL: http://vision.middlebury.edu/flow/flowEval-iccv07.pdf.
479
+
480
+ Returns:
481
+ colorwheel (Tensor[55, 3]): Colorwheel Tensor.
482
+ """
483
+
484
+ RY = 15
485
+ YG = 6
486
+ GC = 4
487
+ CB = 11
488
+ BM = 13
489
+ MR = 6
490
+
491
+ ncols = RY + YG + GC + CB + BM + MR
492
+ colorwheel = torch.zeros((ncols, 3))
493
+ col = 0
494
+
495
+ # RY
496
+ colorwheel[0:RY, 0] = 255
497
+ colorwheel[0:RY, 1] = torch.floor(255 * torch.arange(0, RY) / RY)
498
+ col = col + RY
499
+ # YG
500
+ colorwheel[col : col + YG, 0] = 255 - torch.floor(255 * torch.arange(0, YG) / YG)
501
+ colorwheel[col : col + YG, 1] = 255
502
+ col = col + YG
503
+ # GC
504
+ colorwheel[col : col + GC, 1] = 255
505
+ colorwheel[col : col + GC, 2] = torch.floor(255 * torch.arange(0, GC) / GC)
506
+ col = col + GC
507
+ # CB
508
+ colorwheel[col : col + CB, 1] = 255 - torch.floor(255 * torch.arange(CB) / CB)
509
+ colorwheel[col : col + CB, 2] = 255
510
+ col = col + CB
511
+ # BM
512
+ colorwheel[col : col + BM, 2] = 255
513
+ colorwheel[col : col + BM, 0] = torch.floor(255 * torch.arange(0, BM) / BM)
514
+ col = col + BM
515
+ # MR
516
+ colorwheel[col : col + MR, 2] = 255 - torch.floor(255 * torch.arange(MR) / MR)
517
+ colorwheel[col : col + MR, 0] = 255
518
+ return colorwheel
519
+
520
+
521
+ def _generate_color_palette(num_objects: int):
522
+ palette = torch.tensor([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1])
523
+ return [tuple((i * palette) % 255) for i in range(num_objects)]
524
+
525
+
526
+ def _log_api_usage_once(obj: Any) -> None:
527
+
528
+ """
529
+ Logs API usage(module and name) within an organization.
530
+ In a large ecosystem, it's often useful to track the PyTorch and
531
+ TorchVision APIs usage. This API provides the similar functionality to the
532
+ logging module in the Python stdlib. It can be used for debugging purpose
533
+ to log which methods are used and by default it is inactive, unless the user
534
+ manually subscribes a logger via the `SetAPIUsageLogger method <https://github.com/pytorch/pytorch/blob/eb3b9fe719b21fae13c7a7cf3253f970290a573e/c10/util/Logging.cpp#L114>`_.
535
+ Please note it is triggered only once for the same API call within a process.
536
+ It does not collect any data from open-source users since it is no-op by default.
537
+ For more information, please refer to
538
+ * PyTorch note: https://pytorch.org/docs/stable/notes/large_scale_deployments.html#api-usage-logging;
539
+ * Logging policy: https://github.com/pytorch/vision/issues/5052;
540
+
541
+ Args:
542
+ obj (class instance or method): an object to extract info from.
543
+ """
544
+ if not obj.__module__.startswith("torchvision"):
545
+ return
546
+ name = obj.__class__.__name__
547
+ if isinstance(obj, FunctionType):
548
+ name = obj.__name__
549
+ torch._C._log_api_usage_once(f"{obj.__module__}.{name}")
options/base_options.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import argparse
3
+ import torch
4
+
5
+
6
+ class BaseOptions:
7
+ def __init__(self):
8
+ self.initialized = False
9
+
10
+ def initialize(self, parser):
11
+ parser.add_argument("--arch", type=str, default="CLIP:ViT-L/14", help="see models/__init__.py")
12
+ parser.add_argument("--fix_backbone", default=False)
13
+ parser.add_argument("--fix_encoder", default=True)
14
+
15
+ parser.add_argument("--real_list_path", default="/apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/0_real")
16
+ parser.add_argument("--fake_list_path", default="/apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake")
17
+ parser.add_argument("--data_label", default="train", help="label to decide whether train or validation dataset",)
18
+
19
+ parser.add_argument( "--batch_size", type=int, default=10, help="input batch size")
20
+ parser.add_argument("--gpu_ids", type=str, default="1", help="gpu ids: e.g. 0 0,1,2, 0,2. use -1 for CPU",)
21
+ parser.add_argument("--name", type=str, default="experiment_name", help="name of the experiment. It decides where to store samples and models",)
22
+ parser.add_argument("--num_threads", default=0, type=int, help="# threads for loading data")
23
+ parser.add_argument("--checkpoints_dir", type=str, default="./checkpoints", help="models are saved here",)
24
+ parser.add_argument("--serial_batches",action="store_true",help="if true, takes images in order to make batches, otherwise takes them randomly",)
25
+ parser.add_argument("--suffix", type=str, default="", help="customized suffix: opt.name = opt.name + suffix, e.g., {batch_size}",)
26
+
27
+ # Data augmentation parameters
28
+ parser.add_argument("--rz_interp", type=str, default="bilinear", help="resize interpolation method")
29
+ parser.add_argument("--blur_sig", type=str, default="0", help="blur sigma (comma-separated for range)")
30
+ parser.add_argument("--jpg_method", type=str, default="cv2", help="JPEG compression method")
31
+ parser.add_argument("--jpg_qual", type=str, default="75", help="JPEG quality (comma-separated for range)")
32
+
33
+ # Data loading parameters
34
+ parser.add_argument("--class_bal", action="store_true", help="whether to use class-balanced sampling")
35
+
36
+ self.initialized = True
37
+ return parser
38
+
39
+ def gather_options(self):
40
+ # initialize parser with basic options
41
+ if not self.initialized:
42
+ parser = argparse.ArgumentParser(
43
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter
44
+ )
45
+ parser = self.initialize(parser)
46
+
47
+ # get the basic options
48
+ opt, _ = parser.parse_known_args()
49
+ self.parser = parser
50
+
51
+ return parser.parse_args()
52
+
53
+ def print_options(self, opt):
54
+ message = ""
55
+ message += "----------------- Options ---------------\n"
56
+ for k, v in sorted(vars(opt).items()):
57
+ comment = ""
58
+ default = self.parser.get_default(k)
59
+ if v != default:
60
+ comment = "\t[default: %s]" % str(default)
61
+ message += "{:>25}: {:<30}{}\n".format(str(k), str(v), comment)
62
+ message += "----------------- End -------------------"
63
+ print(message)
64
+
65
+ # save to the disk
66
+ expr_dir = os.path.join(opt.checkpoints_dir, opt.name)
67
+ os.makedirs(expr_dir, exist_ok=True)
68
+ # util.mkdirs(expr_dir)
69
+ file_name = os.path.join(expr_dir, "opt.txt")
70
+ with open(file_name, "wt") as opt_file:
71
+ opt_file.write(message)
72
+ opt_file.write("\n")
73
+
74
+ def parse(self, print_options=True):
75
+ opt = self.gather_options()
76
+ opt.isTrain = self.isTrain # train or test
77
+
78
+ # process opt.suffix
79
+ if opt.suffix:
80
+ suffix = ("_" + opt.suffix.format(**vars(opt))) if opt.suffix != "" else ""
81
+ opt.name = opt.name + suffix
82
+
83
+ if print_options:
84
+ self.print_options(opt)
85
+
86
+ # set gpu ids
87
+ str_ids = opt.gpu_ids.split(",")
88
+ opt.gpu_ids = []
89
+ for str_id in str_ids:
90
+ id = int(str_id)
91
+ if id >= 0:
92
+ opt.gpu_ids.append(id)
93
+ if len(opt.gpu_ids) > 0:
94
+ torch.cuda.set_device(opt.gpu_ids[0])
95
+
96
+ # additional
97
+ # opt.classes = opt.classes.split(',')
98
+ opt.rz_interp = opt.rz_interp.split(",")
99
+ opt.blur_sig = [float(s) for s in opt.blur_sig.split(",")]
100
+ opt.jpg_method = opt.jpg_method.split(",")
101
+ opt.jpg_qual = [int(s) for s in opt.jpg_qual.split(",")]
102
+ if len(opt.jpg_qual) == 2:
103
+ opt.jpg_qual = list(range(opt.jpg_qual[0], opt.jpg_qual[1] + 1))
104
+ elif len(opt.jpg_qual) > 2:
105
+ raise ValueError("Shouldn't have more than 2 values for --jpg_qual.")
106
+
107
+ self.opt = opt
108
+ return self.opt
options/test_options.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .base_options import BaseOptions
2
+
3
+
4
+ class TestOptions(BaseOptions):
5
+ def initialize(self, parser):
6
+ parser = BaseOptions.initialize(self, parser)
7
+ parser.add_argument('--model_path')
8
+ parser.add_argument('--eval', action='store_true', help='use eval mode during test time.')
9
+
10
+ self.isTrain = False
11
+ return parser
options/train_options.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .base_options import BaseOptions
2
+
3
+
4
+ class TrainOptions(BaseOptions):
5
+ def initialize(self, parser):
6
+ parser = BaseOptions.initialize(self, parser)
7
+ parser.add_argument('--optim', type=str, default='adam', help='optim to use [sgd, adam]')
8
+ parser.add_argument('--loss_freq', type=int, default=100, help='frequency of showing loss on tensorboard')
9
+ parser.add_argument('--save_epoch_freq', type=int, default=1,
10
+ help='frequency of saving checkpoints at the end of epochs')
11
+ parser.add_argument('--train_split', type=str, default='train', help='train, val, test, etc')
12
+ parser.add_argument('--val_split', type=str, default='val', help='train, val, test, etc')
13
+ parser.add_argument('--epoch', type=int, default=100, help='total epoches')
14
+ parser.add_argument('--beta1', type=float, default=0.9, help='momentum term of adam')
15
+ parser.add_argument('--lr', type=float, default=2e-9, help='initial learning rate for adam')
16
+ parser.add_argument('--pretrained_model', type=str, default='./checkpoints/experiment_name/model_epoch_29.pth', help='model will fine tune on it if fine_tune is True')
17
+ parser.add_argument('--fine_tune', action='store_true', help='whether to fine-tune from pretrained model')
18
+ parser.add_argument('--weight_decay', type=float, default=1e-4, help='weight decay for optimizer')
19
+ self.isTrain = True
20
+
21
+ return parser
plot_compare_with_lipfd.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """plot_compare_with_lipfd.py — merge LipFD v4 results into X-AVDT's
2
+ merged_long_table.csv, then produce a multi-method comparison figure
3
+ matching the reference grid_auroc.png layout (2x4, 1 empty cell).
4
+
5
+ Usage:
6
+ /opt/conda/envs/LipFD/bin/python plot_compare_with_lipfd.py
7
+ """
8
+ import csv
9
+ import json
10
+ import os
11
+
12
+ import matplotlib.pyplot as plt
13
+ import numpy as np
14
+
15
+
16
+ X_AVDT_CSV = "/apdcephfs_gy4/share_303628665/joywu/research/X-AVDT/results/robustness/compare/merged_long_table.csv"
17
+ LIPFD_RUNS = "/apdcephfs_gy4/share_303628665/joywu/research/LipFD/robustnessv4/runs.json"
18
+ OUT_DIR = "/apdcephfs_gy4/share_303628665/joywu/research/LipFD/robustnessv4/compare"
19
+ os.makedirs(OUT_DIR, exist_ok=True)
20
+
21
+ # Order and display labels mirror the reference figure.
22
+ PERTURBATIONS = [
23
+ ("gaussian_noise", "Gaussian noise"),
24
+ ("block_wise", "Block occlusion"),
25
+ ("jpeg_quality", "JPEG compression"),
26
+ ("pixelate", "Pixelation"),
27
+ ("gaussian_blur", "Gaussian blur"),
28
+ ("color_saturation", "Color saturation"),
29
+ ("color_contrast", "Color contrast"),
30
+ ]
31
+
32
+ # Methods + styling (reference: CTA red circle, X-AVDT blue square, AVH-Align green tri).
33
+ METHODS = [
34
+ ("CTA", "#d62728", "o"),
35
+ ("X-AVDT", "#1f77b4", "s"),
36
+ ("AVH-Align", "#2ca02c", "^"),
37
+ ("LipFD", "#9467bd", "D"), # purple diamond — new method
38
+ ]
39
+
40
+
41
+ def load_xavdt_rows(path):
42
+ with open(path) as f:
43
+ return list(csv.DictReader(f))
44
+
45
+
46
+ def lipfd_to_rows(runs_json):
47
+ """Convert LipFD v4 runs.json to long rows in the same schema as X-AVDT's CSV."""
48
+ runs = json.load(open(runs_json))["runs"]
49
+ # Identify the level=1 baseline (no-op). In LipFD it lives under gaussian_noise/L1.
50
+ baseline = next(r for r in runs if r["level"] == 1)
51
+ bl_metrics = baseline["overall_clip"]
52
+
53
+ rows = []
54
+ perturbs = sorted({r["perturbation"] for r in runs})
55
+ for p in perturbs:
56
+ # Level=1 is the SAME clean baseline for every perturbation.
57
+ rows.append({
58
+ "model": "LipFD", "perturbation": p, "level": "1", "param": "0.0",
59
+ "AUROC": bl_metrics["AUROC"], "AP": bl_metrics["AP"],
60
+ "Accuracy": bl_metrics["Accuracy"], "Acc@EER": bl_metrics["Acc@EER"],
61
+ })
62
+ for r in runs:
63
+ if r["perturbation"] != p or r["level"] == 1:
64
+ continue
65
+ o = r["overall_clip"]
66
+ rows.append({
67
+ "model": "LipFD", "perturbation": p, "level": str(r["level"]),
68
+ "param": str(r["param"]),
69
+ "AUROC": o["AUROC"], "AP": o["AP"],
70
+ "Accuracy": o["Accuracy"], "Acc@EER": o["Acc@EER"],
71
+ })
72
+ return rows
73
+
74
+
75
+ def write_merged(xavdt_rows, lipfd_rows, out_path):
76
+ cols = ["model", "perturbation", "level", "param",
77
+ "AUROC", "AP", "Accuracy", "Acc@EER"]
78
+ with open(out_path, "w", newline="") as f:
79
+ w = csv.DictWriter(f, fieldnames=cols)
80
+ w.writeheader()
81
+ for r in xavdt_rows:
82
+ w.writerow({k: r[k] for k in cols})
83
+ for r in lipfd_rows:
84
+ w.writerow(r)
85
+ print(f" wrote {out_path} ({len(xavdt_rows) + len(lipfd_rows)} rows)")
86
+
87
+
88
+ def index_by(rows, metric):
89
+ """{model: {perturbation: {level: float}}} for the requested metric."""
90
+ out = {}
91
+ for r in rows:
92
+ out.setdefault(r["model"], {}).setdefault(r["perturbation"], {})[
93
+ int(r["level"])] = float(r[metric])
94
+ return out
95
+
96
+
97
+ def plot_grid(rows, metric, out_path, title=None):
98
+ idx = index_by(rows, metric)
99
+ levels = [1, 2, 3, 4, 5]
100
+
101
+ # 2x4 grid (7 perturbations + 1 empty); reference figure layout.
102
+ fig, axes = plt.subplots(2, 4, figsize=(20, 9), sharey=False)
103
+ for ax in axes.flatten():
104
+ ax.set_visible(False)
105
+
106
+ for i, (key, label) in enumerate(PERTURBATIONS):
107
+ ax = axes.flatten()[i]
108
+ ax.set_visible(True)
109
+ for method, color, marker in METHODS:
110
+ ys = [idx.get(method, {}).get(key, {}).get(L, np.nan) for L in levels]
111
+ ax.plot(levels, ys, marker=marker, color=color, label=method,
112
+ linewidth=2.0, markersize=8)
113
+ ax.set_title(label, fontsize=14)
114
+ ax.set_xlabel("Perturbation level (1 = clean, 5 = strongest)", fontsize=11)
115
+ ax.set_ylabel(metric, fontsize=11)
116
+ ax.set_xticks(levels)
117
+ ax.grid(alpha=0.3, linestyle=":")
118
+
119
+ handles, labels = axes.flatten()[0].get_legend_handles_labels()
120
+ fig.legend(handles, labels, loc="upper center", ncol=len(METHODS),
121
+ fontsize=13, frameon=False, bbox_to_anchor=(0.5, 1.02))
122
+ if title:
123
+ fig.suptitle(title, fontsize=14, y=1.05)
124
+ plt.tight_layout()
125
+ plt.savefig(out_path, dpi=140, bbox_inches="tight")
126
+ plt.close()
127
+ print(f" wrote {out_path}")
128
+
129
+
130
+ def main():
131
+ print(f"Loading X-AVDT rows from {X_AVDT_CSV}")
132
+ xavdt_rows = load_xavdt_rows(X_AVDT_CSV)
133
+ print(f" {len(xavdt_rows)} rows ({len({r['model'] for r in xavdt_rows})} methods)")
134
+
135
+ print(f"\nLoading LipFD v4 from {LIPFD_RUNS}")
136
+ lipfd_rows = lipfd_to_rows(LIPFD_RUNS)
137
+ print(f" {len(lipfd_rows)} rows from LipFD")
138
+
139
+ merged_csv = os.path.join(OUT_DIR, "merged_long_table.csv")
140
+ write_merged(xavdt_rows, lipfd_rows, merged_csv)
141
+
142
+ all_rows = xavdt_rows + lipfd_rows
143
+ for metric in ["AUROC", "AP", "Accuracy", "Acc@EER"]:
144
+ out_path = os.path.join(OUT_DIR, f"grid_{metric.lower().replace('@','_')}.png")
145
+ plot_grid(all_rows, metric, out_path)
146
+
147
+
148
+ if __name__ == "__main__":
149
+ main()
plot_robustness.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """plot_robustness.py — visualize robustness sweep results.
2
+
3
+ Reads robustnessv3/runs.json and produces:
4
+ - robustness_overall.png : 4 metrics x 7 perturbations, line plot per metric
5
+ - robustness_per_fake.png: AUROC per (fake-model x perturbation), 1 row per fake
6
+ - robustness_table.csv : flat CSV (perturbation, level, param, metrics)
7
+
8
+ Run:
9
+ /opt/conda/envs/LipFD/bin/python plot_robustness.py \
10
+ --runs robustnessv3/runs.json --out_dir robustnessv3
11
+ """
12
+ import argparse
13
+ import csv as _csv
14
+ import json
15
+ import os
16
+
17
+ import matplotlib.pyplot as plt
18
+ import numpy as np
19
+
20
+
21
+ # Same order as evaluate_robustness.py SEVERITY dict
22
+ PERTURBATIONS = ["color_saturation", "color_contrast", "block_wise",
23
+ "gaussian_noise", "gaussian_blur", "pixelate", "jpeg_quality"]
24
+
25
+ # Visual styling — distinct color per perturbation, consistent across plots
26
+ COLORS = {
27
+ "color_saturation": "#1f77b4",
28
+ "color_contrast": "#ff7f0e",
29
+ "block_wise": "#2ca02c",
30
+ "gaussian_noise": "#d62728",
31
+ "gaussian_blur": "#9467bd",
32
+ "pixelate": "#8c564b",
33
+ "jpeg_quality": "#e377c2",
34
+ }
35
+ MARKERS = {
36
+ "color_saturation": "o",
37
+ "color_contrast": "s",
38
+ "block_wise": "^",
39
+ "gaussian_noise": "D",
40
+ "gaussian_blur": "v",
41
+ "pixelate": "P",
42
+ "jpeg_quality": "X",
43
+ }
44
+
45
+
46
+ def load_runs(path):
47
+ with open(path) as f:
48
+ return json.load(f)["runs"]
49
+
50
+
51
+ def organize(runs):
52
+ """{perturbation: {level: run_dict}} — level 1 baseline copied to every perturbation."""
53
+ out = {p: {} for p in PERTURBATIONS}
54
+ baseline = None
55
+ for r in runs:
56
+ if r["level"] == 1:
57
+ baseline = r
58
+ break
59
+ for r in runs:
60
+ out[r["perturbation"]][r["level"]] = r
61
+ if baseline is not None:
62
+ for p in PERTURBATIONS:
63
+ out[p][1] = baseline
64
+ return out, baseline
65
+
66
+
67
+ def write_csv(runs, csv_path):
68
+ rows = []
69
+ for r in runs:
70
+ o = r["overall_clip"]
71
+ rows.append({
72
+ "perturbation": r["perturbation"],
73
+ "level": r["level"],
74
+ "param": r["param"],
75
+ "n_clips": r["n_clips"],
76
+ "AUROC": o["AUROC"],
77
+ "AP": o["AP"],
78
+ "Accuracy": o["Accuracy"],
79
+ "Acc@EER": o["Acc@EER"],
80
+ "TPR@FPR=1%": o["TPR@FPR=1%"],
81
+ "TPR@FPR=0.1%": o["TPR@FPR=0.1%"],
82
+ })
83
+ rows.sort(key=lambda x: (x["perturbation"], x["level"]))
84
+ with open(csv_path, "w", newline="") as f:
85
+ w = _csv.DictWriter(f, fieldnames=list(rows[0].keys()))
86
+ w.writeheader()
87
+ w.writerows(rows)
88
+ print(f" wrote {csv_path} ({len(rows)} rows)")
89
+
90
+
91
+ def plot_overall(by_pert, out_path, baseline):
92
+ """4 panels: AUROC / Accuracy / Acc@EER / TPR@FPR=1%, level on X axis."""
93
+ metrics = [
94
+ ("AUROC", "AUROC"),
95
+ ("Accuracy", "Accuracy"),
96
+ ("Acc@EER", "Acc@EER"),
97
+ ("TPR@FPR=1%", "TPR@FPR=1%"),
98
+ ]
99
+ fig, axes = plt.subplots(2, 2, figsize=(13, 9))
100
+ axes = axes.flatten()
101
+ levels = [1, 2, 3, 4, 5]
102
+
103
+ for ax, (key, title) in zip(axes, metrics):
104
+ for p in PERTURBATIONS:
105
+ ys = []
106
+ for L in levels:
107
+ r = by_pert[p].get(L)
108
+ if r is None:
109
+ ys.append(np.nan)
110
+ else:
111
+ ys.append(r["overall_clip"][key])
112
+ ax.plot(levels, ys, marker=MARKERS[p], color=COLORS[p],
113
+ label=p, linewidth=1.8, markersize=7)
114
+ if baseline is not None:
115
+ bl = baseline["overall_clip"][key]
116
+ ax.axhline(bl, color="grey", linestyle="--", alpha=0.5, linewidth=1,
117
+ label=f"clean baseline = {bl:.4f}")
118
+ ax.set_title(title, fontsize=12)
119
+ ax.set_xlabel("perturbation level (1=clean, 5=heaviest)")
120
+ ax.set_ylabel(title)
121
+ ax.set_xticks(levels)
122
+ ax.grid(alpha=0.3)
123
+
124
+ # one shared legend on top-right axis
125
+ handles, labels = axes[0].get_legend_handles_labels()
126
+ fig.legend(handles, labels, loc="lower center", ncol=4, fontsize=9,
127
+ frameon=False, bbox_to_anchor=(0.5, -0.02))
128
+ fig.suptitle("LipFD robustness — overall (clip-level), epoch_44 ckpt", fontsize=14)
129
+ plt.tight_layout(rect=[0, 0.04, 1, 0.97])
130
+ plt.savefig(out_path, dpi=140, bbox_inches="tight")
131
+ plt.close()
132
+ print(f" wrote {out_path}")
133
+
134
+
135
+ def plot_per_fake(by_pert, out_path, baseline):
136
+ """1 row per fake model (EDTalk / Float / SadTalk),
137
+ each row = AUROC vs level for every perturbation."""
138
+ fakes = sorted(set(baseline["per_fake_vs_real"].keys()))
139
+ fig, axes = plt.subplots(1, len(fakes), figsize=(5 * len(fakes), 4.5),
140
+ sharey=True)
141
+ if len(fakes) == 1:
142
+ axes = [axes]
143
+ levels = [1, 2, 3, 4, 5]
144
+
145
+ for ax, fm in zip(axes, fakes):
146
+ for p in PERTURBATIONS:
147
+ ys = []
148
+ for L in levels:
149
+ r = by_pert[p].get(L)
150
+ ys.append(r["per_fake_vs_real"][fm]["AUROC"] if r else np.nan)
151
+ ax.plot(levels, ys, marker=MARKERS[p], color=COLORS[p],
152
+ label=p, linewidth=1.6, markersize=6)
153
+ if baseline is not None:
154
+ bl = baseline["per_fake_vs_real"][fm]["AUROC"]
155
+ ax.axhline(bl, color="grey", linestyle="--", alpha=0.5, linewidth=1)
156
+ ax.set_title(f"{fm} + Real (AUROC)")
157
+ ax.set_xlabel("level")
158
+ ax.set_xticks(levels)
159
+ ax.grid(alpha=0.3)
160
+ axes[0].set_ylabel("AUROC")
161
+ handles, labels = axes[0].get_legend_handles_labels()
162
+ fig.legend(handles, labels, loc="lower center", ncol=4, fontsize=9,
163
+ frameon=False, bbox_to_anchor=(0.5, -0.04))
164
+ fig.suptitle("LipFD robustness — per-fake AUROC, epoch_44 ckpt", fontsize=14)
165
+ plt.tight_layout(rect=[0, 0.06, 1, 0.95])
166
+ plt.savefig(out_path, dpi=140, bbox_inches="tight")
167
+ plt.close()
168
+ print(f" wrote {out_path}")
169
+
170
+
171
+ def plot_fairness(by_pert, out_path):
172
+ """3 panels (gender/race4/age_group), each shows F_MEO trend per perturbation."""
173
+ dims = ["gender", "race4", "age_group"]
174
+ fig, axes = plt.subplots(1, 3, figsize=(15, 4.5))
175
+ levels = [1, 2, 3, 4, 5]
176
+ for ax, d in zip(axes, dims):
177
+ for p in PERTURBATIONS:
178
+ ys = []
179
+ for L in levels:
180
+ r = by_pert[p].get(L)
181
+ fb = r["fairness_overall"].get(d) if r else None
182
+ ys.append(fb["F_MEO"] if fb else np.nan)
183
+ ax.plot(levels, ys, marker=MARKERS[p], color=COLORS[p],
184
+ label=p, linewidth=1.6, markersize=6)
185
+ ax.set_title(f"F_MEO ({d}) — lower is fairer")
186
+ ax.set_xlabel("level")
187
+ ax.set_xticks(levels)
188
+ ax.grid(alpha=0.3)
189
+ axes[0].set_ylabel("F_MEO (%)")
190
+ handles, labels = axes[0].get_legend_handles_labels()
191
+ fig.legend(handles, labels, loc="lower center", ncol=4, fontsize=9,
192
+ frameon=False, bbox_to_anchor=(0.5, -0.04))
193
+ fig.suptitle("LipFD robustness — fairness F_MEO across perturbations", fontsize=14)
194
+ plt.tight_layout(rect=[0, 0.06, 1, 0.95])
195
+ plt.savefig(out_path, dpi=140, bbox_inches="tight")
196
+ plt.close()
197
+ print(f" wrote {out_path}")
198
+
199
+
200
+ def parse_args():
201
+ p = argparse.ArgumentParser()
202
+ p.add_argument("--runs", required=True)
203
+ p.add_argument("--out_dir", required=True)
204
+ return p.parse_args()
205
+
206
+
207
+ def main():
208
+ args = parse_args()
209
+ runs = load_runs(args.runs)
210
+ by_pert, baseline = organize(runs)
211
+ os.makedirs(args.out_dir, exist_ok=True)
212
+ write_csv(runs, os.path.join(args.out_dir, "robustness_table.csv"))
213
+ plot_overall(by_pert, os.path.join(args.out_dir, "robustness_overall.png"), baseline)
214
+ plot_per_fake(by_pert, os.path.join(args.out_dir, "robustness_per_fake.png"), baseline)
215
+ plot_fairness(by_pert, os.path.join(args.out_dir, "robustness_fairness.png"))
216
+
217
+
218
+ if __name__ == "__main__":
219
+ main()
preprocess.log ADDED
The diff for this file is too large to render. See raw diff
 
preprocess.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import numpy as np
4
+ import librosa
5
+ import matplotlib.pyplot as plt
6
+ from tqdm import tqdm
7
+ from librosa import feature as audio
8
+
9
+
10
+ """
11
+ Structure of the AVLips dataset:
12
+ AVLips
13
+ ├── 0_real
14
+ ├── 1_fake
15
+ └── wav
16
+ ├── 0_real
17
+ └── 1_fake
18
+ """
19
+
20
+ ############ Custom parameter ##############
21
+ N_EXTRACT = 10 # number of extracted images from video
22
+ WINDOW_LEN = 5 # frames of each window
23
+ MAX_SAMPLE = 100
24
+
25
+ audio_root = "./AVLips/wav"
26
+ video_root = "./AVLips"
27
+ output_root = "./datasets/AVLips"
28
+ ############################################
29
+
30
+ labels = [(0, "0_real"), (1, "1_fake")]
31
+
32
+ def get_spectrogram(audio_file):
33
+ data, sr = librosa.load(audio_file)
34
+ mel = librosa.power_to_db(audio.melspectrogram(y=data, sr=sr), ref=np.min)
35
+ plt.imsave("./temp/mel.png", mel)
36
+
37
+
38
+ def run():
39
+ i = 0
40
+ for label, dataset_name in labels:
41
+ if not os.path.exists(dataset_name):
42
+ os.makedirs(f"{output_root}/{dataset_name}", exist_ok=True)
43
+
44
+ if i == MAX_SAMPLE:
45
+ break
46
+ root = f"{video_root}/{dataset_name}"
47
+ video_list = os.listdir(root)
48
+ print(f"Handling {dataset_name}...")
49
+ for j in tqdm(range(len(video_list))):
50
+ v = video_list[j]
51
+ # load video
52
+ video_capture = cv2.VideoCapture(f"{root}/{v}")
53
+ fps = video_capture.get(cv2.CAP_PROP_FPS)
54
+ frame_count = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
55
+
56
+ # select 10 starting point from frames
57
+ frame_idx = np.linspace(
58
+ 0,
59
+ frame_count - WINDOW_LEN - 1,
60
+ N_EXTRACT,
61
+ endpoint=True,
62
+ dtype=np.uint8,
63
+ ).tolist()
64
+ frame_idx.sort()
65
+ # selected frames
66
+ frame_sequence = [
67
+ i for num in frame_idx for i in range(num, num + WINDOW_LEN)
68
+ ]
69
+ frame_list = []
70
+ current_frame = 0
71
+ while current_frame <= frame_sequence[-1]:
72
+ ret, frame = video_capture.read()
73
+ if not ret:
74
+ print(f"Error in reading frame {v}: {current_frame}")
75
+ break
76
+ if current_frame in frame_sequence:
77
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
78
+ frame_list.append(cv2.resize(frame, (500, 500))) # to floating num
79
+ current_frame += 1
80
+ video_capture.release()
81
+
82
+ # load audio
83
+ name = v.split(".")[0]
84
+ a = f"{audio_root}/{dataset_name}/{name}.wav"
85
+
86
+ group = 0
87
+ get_spectrogram(a)
88
+ mel = plt.imread("./temp/mel.png") * 255 # load spectrogram (int)
89
+ mel = mel.astype(np.uint8)
90
+ mapping = mel.shape[1] / frame_count
91
+ for i in range(len(frame_list)):
92
+ idx = i % WINDOW_LEN
93
+ if idx == 0:
94
+ try:
95
+ begin = np.round(frame_sequence[i] * mapping)
96
+ end = np.round((frame_sequence[i] + WINDOW_LEN) * mapping)
97
+ sub_mel = cv2.resize(
98
+ (mel[:, int(begin) : int(end)]), (500 * WINDOW_LEN, 500)
99
+ )
100
+ x = np.concatenate(frame_list[i : i + WINDOW_LEN], axis=1)
101
+ # print(x.shape)
102
+ # print(sub_mel.shape)
103
+ x = np.concatenate((sub_mel[:, :, :3], x[:, :, :3]), axis=0)
104
+ # print(x.shape)
105
+ plt.imsave(
106
+ f"{output_root}/{dataset_name}/{name}_{group}.png", x
107
+ )
108
+ group = group + 1
109
+ except ValueError:
110
+ print(f"ValueError: {name}")
111
+ continue
112
+ # print(frame_sequence)
113
+ # print(frame_count)
114
+ # print(mel.shape[1])
115
+ # print(mapping)
116
+ # exit(0)
117
+ i += 1
118
+
119
+
120
+ if __name__ == "__main__":
121
+ if not os.path.exists(output_root):
122
+ os.makedirs(output_root, exist_ok=True)
123
+ if not os.path.exists("./temp"):
124
+ os.makedirs("./temp", exist_ok=True)
125
+ run()
preprocess_improved.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import numpy as np
4
+ import librosa
5
+ import matplotlib.pyplot as plt
6
+ from tqdm import tqdm
7
+ from librosa import feature as audio
8
+ import sys
9
+
10
+ """
11
+ Structure of the AVLips dataset:
12
+ AVLips
13
+ ├── 0_real
14
+ ├── 1_fake
15
+ └── wav
16
+ ├── 0_real
17
+ └── 1_fake
18
+ """
19
+
20
+ ############ Custom parameter ##############
21
+ N_EXTRACT = 10 # number of extracted windows from video
22
+ WINDOW_LEN = 5 # frames of each window
23
+ MAX_SAMPLE = 0 # maximum number of videos to process (0 means no limit)
24
+ ############################################
25
+
26
+ audio_root = "./AVLips/wav"
27
+ video_root = "./AVLips"
28
+ output_root = "./datasets/AVLips"
29
+
30
+ # 确保临时目录存在
31
+ os.makedirs("./temp", exist_ok=True)
32
+ os.makedirs(output_root, exist_ok=True)
33
+
34
+
35
+ def get_spectrogram(audio_file, output_path="./temp/mel.png"):
36
+ """
37
+ Generate mel-spectrogram from audio file
38
+
39
+ Args:
40
+ audio_file: path to audio file
41
+ output_path: path to save spectrogram image
42
+ """
43
+ try:
44
+ data, sr = librosa.load(audio_file, sr=16000)
45
+ mel = librosa.power_to_db(audio.melspectrogram(y=data, sr=sr), ref=np.min)
46
+ plt.imsave(output_path, mel)
47
+ return True
48
+ except Exception as e:
49
+ print(f"Error generating spectrogram for {audio_file}: {str(e)}")
50
+ return False
51
+
52
+
53
+ def run():
54
+ labels = [(0, "0_real"), (1, "1_fake")]
55
+
56
+ for label, dataset_name in labels:
57
+ # Create output directory
58
+ os.makedirs(f"{output_root}/{dataset_name}", exist_ok=True)
59
+
60
+ root = f"{video_root}/{dataset_name}"
61
+ if not os.path.exists(root):
62
+ print(f"Warning: {root} does not exist, skipping...")
63
+ continue
64
+
65
+ video_list = os.listdir(root)
66
+ print(f"\nHandling {dataset_name}... (Total: {len(video_list)} videos)")
67
+
68
+ # Limit number of samples if MAX_SAMPLE > 0
69
+ if MAX_SAMPLE > 0:
70
+ video_list = video_list[:MAX_SAMPLE]
71
+ print(f"Limiting to {MAX_SAMPLE} videos")
72
+
73
+ # 断点续传:检查已处理的文件
74
+ output_dir = f"{output_root}/{dataset_name}"
75
+ processed_files = set()
76
+ if os.path.exists(output_dir):
77
+ # 获取已处理的所有输出文件
78
+ for f in os.listdir(output_dir):
79
+ if f.endswith('.png'):
80
+ # 提取视频文件名(去掉 _group.png 后缀)
81
+ parts = f.rsplit('_', 1)
82
+ if len(parts) == 2 and parts[1].startswith('0') and parts[1].endswith('.png'):
83
+ processed_files.add(parts[0] + '.mp4')
84
+
85
+ print(f" - Already processed: {len(processed_files)} videos")
86
+
87
+ # 过滤掉已处理的视频
88
+ video_list = [v for v in video_list if v not in processed_files]
89
+ print(f" - Remaining to process: {len(video_list)} videos")
90
+
91
+ processed_count = 0
92
+ error_count = 0
93
+ skip_count = 0
94
+
95
+ for j in tqdm(range(len(video_list)), desc=dataset_name):
96
+ v = video_list[j]
97
+
98
+ # Check if video file exists
99
+ video_path = f"{root}/{v}"
100
+ if not os.path.exists(video_path):
101
+ print(f"\nWarning: Video file not found: {video_path}")
102
+ skip_count += 1
103
+ continue
104
+
105
+ # Load video
106
+ video_capture = cv2.VideoCapture(video_path)
107
+ if not video_capture.isOpened():
108
+ print(f"\nError: Cannot open video {video_path}")
109
+ error_count += 1
110
+ continue
111
+
112
+ fps = video_capture.get(cv2.CAP_PROP_FPS)
113
+ frame_count = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
114
+
115
+ # Skip if video is too short
116
+ if frame_count < WINDOW_LEN:
117
+ print(f"\nWarning: Video {v} has only {frame_count} frames (need {WINDOW_LEN}), skipping...")
118
+ video_capture.release()
119
+ skip_count += 1
120
+ continue
121
+
122
+ # Select N_EXTRACT starting points from frames
123
+ # Ensure we don't go beyond frame_count - WINDOW_LEN
124
+ max_start = frame_count - WINDOW_LEN
125
+ if max_start <= 0:
126
+ print(f"\nWarning: Video {v} is too short, skipping...")
127
+ video_capture.release()
128
+ error_count += 1
129
+ continue
130
+
131
+ frame_idx = np.linspace(
132
+ 0,
133
+ max_start,
134
+ N_EXTRACT,
135
+ endpoint=True,
136
+ ).astype(int).tolist()
137
+ frame_idx.sort()
138
+
139
+ # Selected frames
140
+ frame_sequence = [
141
+ i for num in frame_idx for i in range(num, num + WINDOW_LEN)
142
+ ]
143
+ frame_list = []
144
+ current_frame = 0
145
+
146
+ # Read frames
147
+ while current_frame <= frame_sequence[-1]:
148
+ ret, frame = video_capture.read()
149
+ if not ret:
150
+ print(f"\nWarning: Error reading frame {current_frame} from {v}")
151
+ break
152
+ if current_frame in frame_sequence:
153
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
154
+ frame_list.append(cv2.resize(frame, (500, 500)))
155
+ current_frame += 1
156
+ video_capture.release()
157
+
158
+ # Check if we got all frames
159
+ if len(frame_list) != len(frame_sequence):
160
+ print(f"\nWarning: Could not read all frames from {v} ({len(frame_list)}/{len(frame_sequence)}), skipping...")
161
+ skip_count += 1
162
+ continue
163
+
164
+ # Load audio
165
+ name = os.path.splitext(v)[0]
166
+ audio_path = f"{audio_root}/{dataset_name}/{name}.wav"
167
+
168
+ if not os.path.exists(audio_path):
169
+ print(f"\nWarning: Audio file not found for {v}: {audio_path}")
170
+ skip_count += 1
171
+ continue
172
+
173
+ # Generate spectrogram
174
+ if not get_spectrogram(audio_path):
175
+ print(f"\nWarning: Could not generate spectrogram for {v}, skipping...")
176
+ skip_count += 1
177
+ continue
178
+
179
+ # Load spectrogram
180
+ mel = plt.imread("./temp/mel.png") * 255 # load spectrogram (int)
181
+ mel = mel.astype(np.uint8)
182
+
183
+ # Calculate mapping from video frames to spectrogram time axis
184
+ mapping = mel.shape[1] / frame_count
185
+
186
+ # Process each window
187
+ group = 0
188
+ for i in range(0, len(frame_list), WINDOW_LEN):
189
+ idx = i // WINDOW_LEN
190
+ try:
191
+ begin = int(np.round(frame_sequence[i] * mapping))
192
+ end = int(np.round((frame_sequence[i] + WINDOW_LEN) * mapping))
193
+
194
+ # Ensure bounds are valid
195
+ begin = max(0, begin)
196
+ end = min(mel.shape[1], end)
197
+
198
+ if end <= begin:
199
+ print(f"\nWarning: Invalid spectrogram bounds for {name}, skipping window {group}")
200
+ continue
201
+
202
+ # Extract and resize spectrogram for this window
203
+ sub_mel = cv2.resize(
204
+ mel[:, begin:end], (500 * WINDOW_LEN, 500)
205
+ )
206
+
207
+ # Concatenate frames horizontally
208
+ x = np.concatenate(frame_list[i:i + WINDOW_LEN], axis=1)
209
+
210
+ # Concatenate spectrogram (top) and frames (bottom)
211
+ x = np.concatenate((sub_mel[:, :, :3], x[:, :, :3]), axis=0)
212
+
213
+ # Save output image
214
+ output_path = f"{output_root}/{dataset_name}/{name}_{group}.png"
215
+ plt.imsave(output_path, x)
216
+ group += 1
217
+
218
+ except Exception as e:
219
+ print(f"\nError processing window {group} for {name}: {str(e)}")
220
+ continue
221
+
222
+ processed_count += 1
223
+
224
+ # Clean up temp file periodically
225
+ if processed_count % 100 == 0:
226
+ if os.path.exists("./temp/mel.png"):
227
+ os.remove("./temp/mel.png")
228
+
229
+ print(f"\n{dataset_name}:")
230
+ print(f" - Processed: {processed_count} videos")
231
+ print(f" - Skipped: {skip_count} videos")
232
+ print(f" - Errors: {error_count} videos")
233
+
234
+
235
+ if __name__ == "__main__":
236
+ print("="*50)
237
+ print("AVLips Preprocessing Script")
238
+ print("="*50)
239
+ print(f"Parameters:")
240
+ print(f" - N_EXTRACT: {N_EXTRACT} windows per video")
241
+ print(f" - WINDOW_LEN: {WINDOW_LEN} frames per window")
242
+ print(f" - MAX_SAMPLE: {MAX_SAMPLE} (0 = no limit)")
243
+ print(f" - Video root: {video_root}")
244
+ print(f" - Audio root: {audio_root}")
245
+ print(f" - Output root: {output_root}")
246
+ print("="*50)
247
+
248
+ # Create necessary directories
249
+ if not os.path.exists(output_root):
250
+ os.makedirs(output_root, exist_ok=True)
251
+ if not os.path.exists("./temp"):
252
+ os.makedirs("./temp", exist_ok=True)
253
+
254
+ run()
255
+
256
+ print("\n" + "="*50)
257
+ print("Processing complete!")
258
+ print("="*50)
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ ftfy==6.1.1
2
+ librosa==0.10.1
3
+ matplotlib==3.8.0
4
+ numpy==1.25.2
5
+ opencv-contrib-python==4.8.1.78
6
+ opencv-python==4.8.1.78
7
+ scikit-learn==1.3.1
8
+ torch==2.1.0
9
+ torchvision==0.16.0
10
+ tqdm==4.66.1
robustness/runs.json ADDED
The diff for this file is too large to render. See raw diff
 
robustness/runs.json.20260625_142029.bak ADDED
@@ -0,0 +1,638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "runs": [
3
+ {
4
+ "ckpt": "checkpoints/lipfd_train/model_epoch_44.pth",
5
+ "saved_at": "2026-06-25 13:39:24",
6
+ "load_info": {
7
+ "missing_count": 0,
8
+ "unexpected_count": 0
9
+ },
10
+ "real_list_path": "datasets/FairTalking-Bench/test/0_real",
11
+ "fake_list_path": "datasets/FairTalking-Bench/test/1_fake",
12
+ "demographics_csv": "/apdcephfs_gy4/share_303628665/joywu/research/test.csv",
13
+ "seed": 42,
14
+ "perturbation": "gaussian_noise",
15
+ "level": 1,
16
+ "param": 0.0,
17
+ "n_clips": 581,
18
+ "n_samples": 11610,
19
+ "overall_clip": {
20
+ "AUROC": 0.99578149069795,
21
+ "AP": 0.9955530611412413,
22
+ "Accuracy@0.50": 0.9483648881239243,
23
+ "Confusion Matrix": [
24
+ [
25
+ 261,
26
+ 30
27
+ ],
28
+ [
29
+ 0,
30
+ 290
31
+ ]
32
+ ],
33
+ "Classification Report": {
34
+ "0": {
35
+ "precision": 1.0,
36
+ "recall": 0.8969072164948454,
37
+ "f1-score": 0.9456521739130436,
38
+ "support": 291.0
39
+ },
40
+ "1": {
41
+ "precision": 0.90625,
42
+ "recall": 1.0,
43
+ "f1-score": 0.9508196721311475,
44
+ "support": 290.0
45
+ },
46
+ "accuracy": 0.9483648881239243,
47
+ "macro avg": {
48
+ "precision": 0.953125,
49
+ "recall": 0.9484536082474226,
50
+ "f1-score": 0.9482359230220956,
51
+ "support": 581.0
52
+ },
53
+ "weighted avg": {
54
+ "precision": 0.9532056798623064,
55
+ "recall": 0.9483648881239243,
56
+ "f1-score": 0.9482314759496187,
57
+ "support": 581.0
58
+ }
59
+ },
60
+ "EER_threshold": 0.7245295996467273,
61
+ "Acc@EER": 0.9690189328743546,
62
+ "TPR@FPR=1%": 0.8344827586206897,
63
+ "TPR@FPR=0.1%": 0.7206896551724138,
64
+ "Accuracy": 0.9483648881239243
65
+ },
66
+ "per_fake_vs_real": {
67
+ "EDTalk": {
68
+ "AUROC": 0.9955924099805767,
69
+ "AP": 0.9867113482687109,
70
+ "Accuracy@0.50": 0.9216710182767625,
71
+ "Confusion Matrix": [
72
+ [
73
+ 261,
74
+ 30
75
+ ],
76
+ [
77
+ 0,
78
+ 92
79
+ ]
80
+ ],
81
+ "Classification Report": {
82
+ "0": {
83
+ "precision": 1.0,
84
+ "recall": 0.8969072164948454,
85
+ "f1-score": 0.9456521739130436,
86
+ "support": 291.0
87
+ },
88
+ "1": {
89
+ "precision": 0.7540983606557377,
90
+ "recall": 1.0,
91
+ "f1-score": 0.8598130841121495,
92
+ "support": 92.0
93
+ },
94
+ "accuracy": 0.9216710182767625,
95
+ "macro avg": {
96
+ "precision": 0.8770491803278688,
97
+ "recall": 0.9484536082474226,
98
+ "f1-score": 0.9027326290125965,
99
+ "support": 383.0
100
+ },
101
+ "weighted avg": {
102
+ "precision": 0.9409322432906733,
103
+ "recall": 0.9216710182767625,
104
+ "f1-score": 0.9250328625248392,
105
+ "support": 383.0
106
+ }
107
+ },
108
+ "EER_threshold": 0.6978994131088256,
109
+ "Acc@EER": 0.9608355091383812,
110
+ "TPR@FPR=1%": 0.8586956521739131,
111
+ "TPR@FPR=0.1%": 0.7391304347826086,
112
+ "Accuracy": 0.9216710182767625
113
+ },
114
+ "Float": {
115
+ "AUROC": 0.9957375099127677,
116
+ "AP": 0.9882197470249718,
117
+ "Accuracy@0.50": 0.9240506329113924,
118
+ "Confusion Matrix": [
119
+ [
120
+ 261,
121
+ 30
122
+ ],
123
+ [
124
+ 0,
125
+ 104
126
+ ]
127
+ ],
128
+ "Classification Report": {
129
+ "0": {
130
+ "precision": 1.0,
131
+ "recall": 0.8969072164948454,
132
+ "f1-score": 0.9456521739130436,
133
+ "support": 291.0
134
+ },
135
+ "1": {
136
+ "precision": 0.7761194029850746,
137
+ "recall": 1.0,
138
+ "f1-score": 0.8739495798319328,
139
+ "support": 104.0
140
+ },
141
+ "accuracy": 0.9240506329113924,
142
+ "macro avg": {
143
+ "precision": 0.8880597014925373,
144
+ "recall": 0.9484536082474226,
145
+ "f1-score": 0.9098008768724881,
146
+ "support": 395.0
147
+ },
148
+ "weighted avg": {
149
+ "precision": 0.9410542225580957,
150
+ "recall": 0.9240506329113924,
151
+ "f1-score": 0.9267735162309284,
152
+ "support": 395.0
153
+ }
154
+ },
155
+ "EER_threshold": 0.7245295996467273,
156
+ "Acc@EER": 0.9696202531645569,
157
+ "TPR@FPR=1%": 0.8269230769230769,
158
+ "TPR@FPR=0.1%": 0.7403846153846154,
159
+ "Accuracy": 0.9240506329113924
160
+ },
161
+ "SadTalk": {
162
+ "AUROC": 0.9960152080134532,
163
+ "AP": 0.9872312860680599,
164
+ "Accuracy@0.50": 0.922077922077922,
165
+ "Confusion Matrix": [
166
+ [
167
+ 261,
168
+ 30
169
+ ],
170
+ [
171
+ 0,
172
+ 94
173
+ ]
174
+ ],
175
+ "Classification Report": {
176
+ "0": {
177
+ "precision": 1.0,
178
+ "recall": 0.8969072164948454,
179
+ "f1-score": 0.9456521739130436,
180
+ "support": 291.0
181
+ },
182
+ "1": {
183
+ "precision": 0.7580645161290323,
184
+ "recall": 1.0,
185
+ "f1-score": 0.8623853211009175,
186
+ "support": 94.0
187
+ },
188
+ "accuracy": 0.922077922077922,
189
+ "macro avg": {
190
+ "precision": 0.8790322580645161,
191
+ "recall": 0.9484536082474226,
192
+ "f1-score": 0.9040187475069805,
193
+ "support": 385.0
194
+ },
195
+ "weighted avg": {
196
+ "precision": 0.9409300377042312,
197
+ "recall": 0.922077922077922,
198
+ "f1-score": 0.9253220851744985,
199
+ "support": 385.0
200
+ }
201
+ },
202
+ "EER_threshold": 0.7151398360729218,
203
+ "Acc@EER": 0.9636363636363636,
204
+ "TPR@FPR=1%": 0.8191489361702128,
205
+ "TPR@FPR=0.1%": 0.6808510638297872,
206
+ "Accuracy": 0.922077922077922
207
+ }
208
+ },
209
+ "fairness_overall": {
210
+ "gender": {
211
+ "F_FPR": 0.7227208313651395,
212
+ "F_MEO": 1.445441662730279,
213
+ "F_DP": 0.28440062568138025,
214
+ "F_OAE": 0.3709058159927947,
215
+ "groups": {
216
+ "Female": {
217
+ "n": 289,
218
+ "fpr": 0.1103448275862069,
219
+ "tpr": 1.0,
220
+ "acc": 0.9446366782006921,
221
+ "dp": 0.5536332179930796
222
+ },
223
+ "Male": {
224
+ "n": 292,
225
+ "fpr": 0.0958904109589041,
226
+ "tpr": 1.0,
227
+ "acc": 0.952054794520548,
228
+ "dp": 0.547945205479452
229
+ }
230
+ }
231
+ },
232
+ "race4": {
233
+ "F_FPR": 6.209116070676719,
234
+ "F_MEO": 16.216216216216218,
235
+ "F_DP": 2.491691050830286,
236
+ "F_OAE": 3.139413058000952,
237
+ "groups": {
238
+ "Asian": {
239
+ "n": 143,
240
+ "fpr": 0.1388888888888889,
241
+ "tpr": 1.0,
242
+ "acc": 0.9300699300699301,
243
+ "dp": 0.5664335664335665
244
+ },
245
+ "Black": {
246
+ "n": 146,
247
+ "fpr": 0.16216216216216217,
248
+ "tpr": 1.0,
249
+ "acc": 0.9178082191780822,
250
+ "dp": 0.5753424657534246
251
+ },
252
+ "Indian": {
253
+ "n": 145,
254
+ "fpr": 0.0,
255
+ "tpr": 1.0,
256
+ "acc": 1.0,
257
+ "dp": 0.5103448275862069
258
+ },
259
+ "White": {
260
+ "n": 147,
261
+ "fpr": 0.10810810810810811,
262
+ "tpr": 1.0,
263
+ "acc": 0.9455782312925171,
264
+ "dp": 0.5510204081632653
265
+ }
266
+ }
267
+ },
268
+ "age_group": {
269
+ "F_FPR": 12.845213079874917,
270
+ "F_MEO": 37.5,
271
+ "F_DP": 6.479476581570534,
272
+ "F_OAE": 6.4214750331720065,
273
+ "groups": {
274
+ "0-9": {
275
+ "n": 96,
276
+ "fpr": 0.0,
277
+ "tpr": 1.0,
278
+ "acc": 1.0,
279
+ "dp": 0.5
280
+ },
281
+ "10-19": {
282
+ "n": 97,
283
+ "fpr": 0.02040816326530612,
284
+ "tpr": 1.0,
285
+ "acc": 0.9896907216494846,
286
+ "dp": 0.5051546391752577
287
+ },
288
+ "20-29": {
289
+ "n": 96,
290
+ "fpr": 0.020833333333333332,
291
+ "tpr": 1.0,
292
+ "acc": 0.9895833333333334,
293
+ "dp": 0.5104166666666666
294
+ },
295
+ "30-39": {
296
+ "n": 98,
297
+ "fpr": 0.08163265306122448,
298
+ "tpr": 1.0,
299
+ "acc": 0.9591836734693877,
300
+ "dp": 0.5408163265306123
301
+ },
302
+ "40-49": {
303
+ "n": 98,
304
+ "fpr": 0.12244897959183673,
305
+ "tpr": 1.0,
306
+ "acc": 0.9387755102040817,
307
+ "dp": 0.5612244897959183
308
+ },
309
+ "50+": {
310
+ "n": 96,
311
+ "fpr": 0.375,
312
+ "tpr": 1.0,
313
+ "acc": 0.8125,
314
+ "dp": 0.6875
315
+ }
316
+ }
317
+ }
318
+ }
319
+ },
320
+ {
321
+ "ckpt": "checkpoints/lipfd_train/model_epoch_44.pth",
322
+ "saved_at": "2026-06-25 14:19:44",
323
+ "load_info": {
324
+ "missing_count": 0,
325
+ "unexpected_count": 0
326
+ },
327
+ "real_list_path": "datasets/FairTalking-Bench/test/0_real",
328
+ "fake_list_path": "datasets/FairTalking-Bench/test/1_fake",
329
+ "demographics_csv": "/apdcephfs_gy4/share_303628665/joywu/research/test.csv",
330
+ "seed": 42,
331
+ "perturbation": "gaussian_noise",
332
+ "level": 3,
333
+ "param": 0.005,
334
+ "n_clips": 581,
335
+ "n_samples": 11610,
336
+ "overall_clip": {
337
+ "AUROC": 0.9772366394122525,
338
+ "AP": 0.9742001425382162,
339
+ "Accuracy@0.50": 0.919104991394148,
340
+ "Confusion Matrix": [
341
+ [
342
+ 249,
343
+ 42
344
+ ],
345
+ [
346
+ 5,
347
+ 285
348
+ ]
349
+ ],
350
+ "Classification Report": {
351
+ "0": {
352
+ "precision": 0.9803149606299213,
353
+ "recall": 0.8556701030927835,
354
+ "f1-score": 0.9137614678899082,
355
+ "support": 291.0
356
+ },
357
+ "1": {
358
+ "precision": 0.8715596330275229,
359
+ "recall": 0.9827586206896551,
360
+ "f1-score": 0.9238249594813615,
361
+ "support": 290.0
362
+ },
363
+ "accuracy": 0.919104991394148,
364
+ "macro avg": {
365
+ "precision": 0.9259372968287221,
366
+ "recall": 0.9192143618912193,
367
+ "f1-score": 0.9187932136856348,
368
+ "support": 581.0
369
+ },
370
+ "weighted avg": {
371
+ "precision": 0.9260308900538533,
372
+ "recall": 0.919104991394148,
373
+ "f1-score": 0.9187845531937316,
374
+ "support": 581.0
375
+ }
376
+ },
377
+ "EER_threshold": 0.6816619575023651,
378
+ "Acc@EER": 0.9156626506024096,
379
+ "TPR@FPR=1%": 0.496551724137931,
380
+ "TPR@FPR=0.1%": 0.3,
381
+ "Accuracy": 0.919104991394148
382
+ },
383
+ "per_fake_vs_real": {
384
+ "EDTalk": {
385
+ "AUROC": 0.9786717466009263,
386
+ "AP": 0.9356621957045247,
387
+ "Accuracy@0.50": 0.8877284595300261,
388
+ "Confusion Matrix": [
389
+ [
390
+ 249,
391
+ 42
392
+ ],
393
+ [
394
+ 1,
395
+ 91
396
+ ]
397
+ ],
398
+ "Classification Report": {
399
+ "0": {
400
+ "precision": 0.996,
401
+ "recall": 0.8556701030927835,
402
+ "f1-score": 0.920517560073937,
403
+ "support": 291.0
404
+ },
405
+ "1": {
406
+ "precision": 0.6842105263157895,
407
+ "recall": 0.9891304347826086,
408
+ "f1-score": 0.8088888888888889,
409
+ "support": 92.0
410
+ },
411
+ "accuracy": 0.8877284595300261,
412
+ "macro avg": {
413
+ "precision": 0.8401052631578947,
414
+ "recall": 0.922400268937696,
415
+ "f1-score": 0.864703224481413,
416
+ "support": 383.0
417
+ },
418
+ "weighted avg": {
419
+ "precision": 0.9211054005771608,
420
+ "recall": 0.8877284595300261,
421
+ "f1-score": 0.8937033622958053,
422
+ "support": 383.0
423
+ }
424
+ },
425
+ "EER_threshold": 0.6643097837766011,
426
+ "Acc@EER": 0.9242819843342036,
427
+ "TPR@FPR=1%": 0.5217391304347826,
428
+ "TPR@FPR=0.1%": 0.30434782608695654,
429
+ "Accuracy": 0.8877284595300261
430
+ },
431
+ "Float": {
432
+ "AUROC": 0.9747885276235791,
433
+ "AP": 0.9299015308451564,
434
+ "Accuracy@0.50": 0.8860759493670886,
435
+ "Confusion Matrix": [
436
+ [
437
+ 249,
438
+ 42
439
+ ],
440
+ [
441
+ 3,
442
+ 101
443
+ ]
444
+ ],
445
+ "Classification Report": {
446
+ "0": {
447
+ "precision": 0.9880952380952381,
448
+ "recall": 0.8556701030927835,
449
+ "f1-score": 0.9171270718232044,
450
+ "support": 291.0
451
+ },
452
+ "1": {
453
+ "precision": 0.7062937062937062,
454
+ "recall": 0.9711538461538461,
455
+ "f1-score": 0.8178137651821862,
456
+ "support": 104.0
457
+ },
458
+ "accuracy": 0.8860759493670886,
459
+ "macro avg": {
460
+ "precision": 0.8471944721944722,
461
+ "recall": 0.9134119746233148,
462
+ "f1-score": 0.8674704185026954,
463
+ "support": 395.0
464
+ },
465
+ "weighted avg": {
466
+ "precision": 0.9138993917474929,
467
+ "recall": 0.8860759493670886,
468
+ "f1-score": 0.8909787581759492,
469
+ "support": 395.0
470
+ }
471
+ },
472
+ "EER_threshold": 0.6720969811081886,
473
+ "Acc@EER": 0.9215189873417722,
474
+ "TPR@FPR=1%": 0.4807692307692308,
475
+ "TPR@FPR=0.1%": 0.27884615384615385,
476
+ "Accuracy": 0.8860759493670886
477
+ },
478
+ "SadTalk": {
479
+ "AUROC": 0.978540615632083,
480
+ "AP": 0.9313019980822816,
481
+ "Accuracy@0.50": 0.8883116883116883,
482
+ "Confusion Matrix": [
483
+ [
484
+ 249,
485
+ 42
486
+ ],
487
+ [
488
+ 1,
489
+ 93
490
+ ]
491
+ ],
492
+ "Classification Report": {
493
+ "0": {
494
+ "precision": 0.996,
495
+ "recall": 0.8556701030927835,
496
+ "f1-score": 0.920517560073937,
497
+ "support": 291.0
498
+ },
499
+ "1": {
500
+ "precision": 0.6888888888888889,
501
+ "recall": 0.9893617021276596,
502
+ "f1-score": 0.812227074235808,
503
+ "support": 94.0
504
+ },
505
+ "accuracy": 0.8883116883116883,
506
+ "macro avg": {
507
+ "precision": 0.8424444444444444,
508
+ "recall": 0.9225159026102215,
509
+ "f1-score": 0.8663723171548725,
510
+ "support": 385.0
511
+ },
512
+ "weighted avg": {
513
+ "precision": 0.9210170274170275,
514
+ "recall": 0.8883116883116883,
515
+ "f1-score": 0.8940778050900822,
516
+ "support": 385.0
517
+ }
518
+ },
519
+ "EER_threshold": 0.6858754555384318,
520
+ "Acc@EER": 0.9246753246753247,
521
+ "TPR@FPR=1%": 0.48936170212765956,
522
+ "TPR@FPR=0.1%": 0.3191489361702128,
523
+ "Accuracy": 0.8883116883116883
524
+ }
525
+ },
526
+ "fairness_overall": {
527
+ "gender": {
528
+ "F_FPR": 6.235238545111006,
529
+ "F_MEO": 12.470477090222012,
530
+ "F_DP": 3.9051760913874025,
531
+ "F_OAE": 2.2793525145755336,
532
+ "groups": {
533
+ "Female": {
534
+ "n": 289,
535
+ "fpr": 0.20689655172413793,
536
+ "tpr": 1.0,
537
+ "acc": 0.8961937716262975,
538
+ "dp": 0.6020761245674741
539
+ },
540
+ "Male": {
541
+ "n": 292,
542
+ "fpr": 0.0821917808219178,
543
+ "tpr": 0.9657534246575342,
544
+ "acc": 0.9417808219178082,
545
+ "dp": 0.523972602739726
546
+ }
547
+ }
548
+ },
549
+ "race4": {
550
+ "F_FPR": 6.769850575850797,
551
+ "F_MEO": 16.627543035993742,
552
+ "F_DP": 2.418668958109545,
553
+ "F_OAE": 3.900207180603046,
554
+ "groups": {
555
+ "Asian": {
556
+ "n": 143,
557
+ "fpr": 0.19444444444444445,
558
+ "tpr": 0.9859154929577465,
559
+ "acc": 0.8951048951048951,
560
+ "dp": 0.5874125874125874
561
+ },
562
+ "Black": {
563
+ "n": 146,
564
+ "fpr": 0.16216216216216217,
565
+ "tpr": 0.9722222222222222,
566
+ "acc": 0.9041095890410958,
567
+ "dp": 0.5616438356164384
568
+ },
569
+ "Indian": {
570
+ "n": 145,
571
+ "fpr": 0.028169014084507043,
572
+ "tpr": 1.0,
573
+ "acc": 0.9862068965517241,
574
+ "dp": 0.5241379310344828
575
+ },
576
+ "White": {
577
+ "n": 147,
578
+ "fpr": 0.1891891891891892,
579
+ "tpr": 0.9726027397260274,
580
+ "acc": 0.891156462585034,
581
+ "dp": 0.5782312925170068
582
+ }
583
+ }
584
+ },
585
+ "age_group": {
586
+ "F_FPR": 10.871458596442137,
587
+ "F_MEO": 31.335034013605444,
588
+ "F_DP": 5.353741021611331,
589
+ "F_OAE": 5.606466598928446,
590
+ "groups": {
591
+ "0-9": {
592
+ "n": 96,
593
+ "fpr": 0.041666666666666664,
594
+ "tpr": 0.9791666666666666,
595
+ "acc": 0.96875,
596
+ "dp": 0.5104166666666666
597
+ },
598
+ "10-19": {
599
+ "n": 97,
600
+ "fpr": 0.04081632653061224,
601
+ "tpr": 1.0,
602
+ "acc": 0.979381443298969,
603
+ "dp": 0.5154639175257731
604
+ },
605
+ "20-29": {
606
+ "n": 96,
607
+ "fpr": 0.08333333333333333,
608
+ "tpr": 0.9791666666666666,
609
+ "acc": 0.9479166666666666,
610
+ "dp": 0.53125
611
+ },
612
+ "30-39": {
613
+ "n": 98,
614
+ "fpr": 0.16326530612244897,
615
+ "tpr": 0.9795918367346939,
616
+ "acc": 0.9081632653061225,
617
+ "dp": 0.5714285714285714
618
+ },
619
+ "40-49": {
620
+ "n": 98,
621
+ "fpr": 0.1836734693877551,
622
+ "tpr": 0.9795918367346939,
623
+ "acc": 0.8979591836734694,
624
+ "dp": 0.5816326530612245
625
+ },
626
+ "50+": {
627
+ "n": 96,
628
+ "fpr": 0.3541666666666667,
629
+ "tpr": 0.9791666666666666,
630
+ "acc": 0.8125,
631
+ "dp": 0.6666666666666666
632
+ }
633
+ }
634
+ }
635
+ }
636
+ }
637
+ ]
638
+ }
robustness/sweep.log ADDED
The diff for this file is too large to render. See raw diff
 
robustness/sweepv2.log ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0
 
 
 
 
 
 
 
 
 
 
 
1
 
 
 
 
 
 
 
 
 
 
 
1
+ nohup: ignoring input
2
+ ===== baseline (no-op, level=1) =====
3
+ [robustness] perturbation=gaussian_noise level=1 param=0.0 ckpt=checkpoints/lipfd_train/model_epoch_10.pth
4
+ [OK] Strict checkpoint match: all 770 keys consumed.
5
+
6
+ warnings.warn(
7
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
8
+ warnings.warn(
9
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
10
+ warnings.warn(
11
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
12
+ warnings.warn(
13
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
14
+ warnings.warn(
15
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
16
+ warnings.warn(
17
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
18
+ warnings.warn(
19
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
20
+ warnings.warn(
21
+
22
 
23
+ [gaussian_noise L1] overall_clip AUROC=0.9710 AP=0.9624 Acc=0.9053 Acc@EER=0.9191 TPR@1%FPR=0.6103 TPR@0.1%FPR=0.0931 (n_clips=581 n_samples=11610)
24
+ [EDTalk+Real] AUROC=0.9696 AP=0.8996 Acc=0.8799 Acc@EER=0.9217
25
+ [Float+Real] AUROC=0.9706 AP=0.9096 Acc=0.8810 Acc@EER=0.9241
26
+ [SadTalk+Real] AUROC=0.9728 AP=0.8992 Acc=0.8857 Acc@EER=0.9091
27
+ fairness[gender] F_FPR=2.45 F_MEO=4.91 F_DP=1.14 F_OAE=1.25
28
+ fairness[race4] F_FPR=5.13 F_MEO=13.81 F_DP=1.99 F_OAE=3.10
29
+ fairness[age_group] F_FPR=9.97 F_MEO=29.29 F_DP=5.91 F_OAE=4.33
30
+
31
+ >>> Appended run to /apdcephfs_gy4/share_303628665/joywu/research/LipFD/robustnessv2/runs.json
32
+
33
 
34
+ [color_saturation L2] overall_clip AUROC=0.9337 AP=0.9299 Acc=0.8451 Acc@EER=0.8520 TPR@1%FPR=0.5069 TPR@0.1%FPR=0.0345 (n_clips=581 n_samples=11610)
35
+ [EDTalk+Real] AUROC=0.9379 AP=0.8596 Acc=0.8668 Acc@EER=0.8433
36
+ [Float+Real] AUROC=0.9299 AP=0.8253 Acc=0.8430 Acc@EER=0.8456
37
+ [SadTalk+Real] AUROC=0.9338 AP=0.8289 Acc=0.8623 Acc@EER=0.8597
38
+ fairness[gender] F_FPR=1.42 F_MEO=6.65 F_DP=2.31 F_OAE=0.95
39
+ fairness[race4] F_FPR=4.88 F_MEO=13.29 F_DP=2.17 F_OAE=2.68
40
+ fairness[age_group] F_FPR=8.98 F_MEO=29.17 F_DP=5.14 F_OAE=4.95
41
+
42
+ >>> Appended run to /apdcephfs_gy4/share_303628665/joywu/research/LipFD/robustnessv2/runs.json
robustness/sweepv3.log ADDED
The diff for this file is too large to render. See raw diff
 
robustness/test_clean.json ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "ckpt": "/apdcephfs_gy4/share_303628665/joywu/research/LipFD/checkpoints/lipfd_train/model_epoch_5.pth",
3
+ "saved_at": "2026-06-25 21:18:28",
4
+ "load_info": {
5
+ "missing_count": 0,
6
+ "unexpected_count": 0
7
+ },
8
+ "real_list_path": "datasets/FairTalking-Bench/test/0_real",
9
+ "fake_list_path": "datasets/FairTalking-Bench/test/1_fake",
10
+ "demographics_csv": "/apdcephfs_gy4/share_303628665/joywu/research/test.csv",
11
+ "seed": 42,
12
+ "n_clips": 581,
13
+ "n_samples": 11610,
14
+ "overall_clip": {
15
+ "AUROC": 0.9333807323142551,
16
+ "AP": 0.9327153892461657,
17
+ "Accuracy@0.50": 0.8450946643717728,
18
+ "Confusion Matrix": [
19
+ [
20
+ 242,
21
+ 49
22
+ ],
23
+ [
24
+ 41,
25
+ 249
26
+ ]
27
+ ],
28
+ "Classification Report": {
29
+ "0": {
30
+ "precision": 0.8551236749116607,
31
+ "recall": 0.8316151202749141,
32
+ "f1-score": 0.843205574912892,
33
+ "support": 291.0
34
+ },
35
+ "1": {
36
+ "precision": 0.8355704697986577,
37
+ "recall": 0.8586206896551725,
38
+ "f1-score": 0.8469387755102041,
39
+ "support": 290.0
40
+ },
41
+ "accuracy": 0.8450946643717728,
42
+ "macro avg": {
43
+ "precision": 0.8453470723551593,
44
+ "recall": 0.8451179049650432,
45
+ "f1-score": 0.8450721752115481,
46
+ "support": 581.0
47
+ },
48
+ "weighted avg": {
49
+ "precision": 0.8453638995540517,
50
+ "recall": 0.8450946643717728,
51
+ "f1-score": 0.8450689624743731,
52
+ "support": 581.0
53
+ }
54
+ },
55
+ "EER_threshold": 0.5060416251420975,
56
+ "Acc@EER": 0.8433734939759037,
57
+ "TPR@FPR=1%": 0.5137931034482759,
58
+ "TPR@FPR=0.1%": 0.0896551724137931,
59
+ "Accuracy": 0.8450946643717728
60
+ },
61
+ "per_fake_vs_real": {
62
+ "EDTalk": {
63
+ "AUROC": 0.9378828626923652,
64
+ "AP": 0.8637361754335757,
65
+ "Accuracy@0.50": 0.8407310704960835,
66
+ "Confusion Matrix": [
67
+ [
68
+ 242,
69
+ 49
70
+ ],
71
+ [
72
+ 12,
73
+ 80
74
+ ]
75
+ ],
76
+ "Classification Report": {
77
+ "0": {
78
+ "precision": 0.952755905511811,
79
+ "recall": 0.8316151202749141,
80
+ "f1-score": 0.8880733944954128,
81
+ "support": 291.0
82
+ },
83
+ "1": {
84
+ "precision": 0.6201550387596899,
85
+ "recall": 0.8695652173913043,
86
+ "f1-score": 0.7239819004524886,
87
+ "support": 92.0
88
+ },
89
+ "accuracy": 0.8407310704960835,
90
+ "macro avg": {
91
+ "precision": 0.7864554721357504,
92
+ "recall": 0.8505901688331092,
93
+ "f1-score": 0.8060276474739507,
94
+ "support": 383.0
95
+ },
96
+ "weighted avg": {
97
+ "precision": 0.8728622247254006,
98
+ "recall": 0.8407310704960835,
99
+ "f1-score": 0.8486571609394101,
100
+ "support": 383.0
101
+ }
102
+ },
103
+ "EER_threshold": 0.5170380979776382,
104
+ "Acc@EER": 0.8746736292428199,
105
+ "TPR@FPR=1%": 0.5760869565217391,
106
+ "TPR@FPR=0.1%": 0.10869565217391304,
107
+ "Accuracy": 0.8407310704960835
108
+ },
109
+ "Float": {
110
+ "AUROC": 0.9278680941052074,
111
+ "AP": 0.8317222383016976,
112
+ "Accuracy@0.50": 0.8354430379746836,
113
+ "Confusion Matrix": [
114
+ [
115
+ 242,
116
+ 49
117
+ ],
118
+ [
119
+ 16,
120
+ 88
121
+ ]
122
+ ],
123
+ "Classification Report": {
124
+ "0": {
125
+ "precision": 0.937984496124031,
126
+ "recall": 0.8316151202749141,
127
+ "f1-score": 0.8816029143897997,
128
+ "support": 291.0
129
+ },
130
+ "1": {
131
+ "precision": 0.6423357664233577,
132
+ "recall": 0.8461538461538461,
133
+ "f1-score": 0.7302904564315352,
134
+ "support": 104.0
135
+ },
136
+ "accuracy": 0.8354430379746836,
137
+ "macro avg": {
138
+ "precision": 0.7901601312736943,
139
+ "recall": 0.8388844832143801,
140
+ "f1-score": 0.8059466854106674,
141
+ "support": 395.0
142
+ },
143
+ "weighted avg": {
144
+ "precision": 0.8601428052661323,
145
+ "recall": 0.8354430379746836,
146
+ "f1-score": 0.841763684952687,
147
+ "support": 395.0
148
+ }
149
+ },
150
+ "EER_threshold": 0.5007072478532791,
151
+ "Acc@EER": 0.8379746835443038,
152
+ "TPR@FPR=1%": 0.46153846153846156,
153
+ "TPR@FPR=0.1%": 0.07692307692307693,
154
+ "Accuracy": 0.8354430379746836
155
+ },
156
+ "SadTalk": {
157
+ "AUROC": 0.9350734810265409,
158
+ "AP": 0.8440944635739278,
159
+ "Accuracy@0.50": 0.8389610389610389,
160
+ "Confusion Matrix": [
161
+ [
162
+ 242,
163
+ 49
164
+ ],
165
+ [
166
+ 13,
167
+ 81
168
+ ]
169
+ ],
170
+ "Classification Report": {
171
+ "0": {
172
+ "precision": 0.9490196078431372,
173
+ "recall": 0.8316151202749141,
174
+ "f1-score": 0.8864468864468865,
175
+ "support": 291.0
176
+ },
177
+ "1": {
178
+ "precision": 0.6230769230769231,
179
+ "recall": 0.8617021276595744,
180
+ "f1-score": 0.7232142857142857,
181
+ "support": 94.0
182
+ },
183
+ "accuracy": 0.8389610389610389,
184
+ "macro avg": {
185
+ "precision": 0.7860482654600301,
186
+ "recall": 0.8466586239672442,
187
+ "f1-score": 0.8048305860805861,
188
+ "support": 385.0
189
+ },
190
+ "weighted avg": {
191
+ "precision": 0.86943879649762,
192
+ "recall": 0.8389610389610389,
193
+ "f1-score": 0.8465926930212644,
194
+ "support": 385.0
195
+ }
196
+ },
197
+ "EER_threshold": 0.5093957483768463,
198
+ "Acc@EER": 0.8519480519480519,
199
+ "TPR@FPR=1%": 0.5106382978723404,
200
+ "TPR@FPR=0.1%": 0.0851063829787234,
201
+ "Accuracy": 0.8389610389610389
202
+ }
203
+ },
204
+ "fairness_overall": {
205
+ "gender": {
206
+ "F_FPR": 1.776098252243742,
207
+ "F_MEO": 3.552196504487484,
208
+ "F_DP": 1.297577854671278,
209
+ "F_OAE": 0.42423093330805073,
210
+ "groups": {
211
+ "Female": {
212
+ "n": 289,
213
+ "fpr": 0.18620689655172415,
214
+ "tpr": 0.8680555555555556,
215
+ "acc": 0.8408304498269896,
216
+ "dp": 0.5259515570934256
217
+ },
218
+ "Male": {
219
+ "n": 292,
220
+ "fpr": 0.1506849315068493,
221
+ "tpr": 0.8493150684931506,
222
+ "acc": 0.8493150684931506,
223
+ "dp": 0.5
224
+ }
225
+ }
226
+ },
227
+ "race4": {
228
+ "F_FPR": 7.01785844183937,
229
+ "F_MEO": 19.366197183098592,
230
+ "F_DP": 1.852662982397705,
231
+ "F_OAE": 4.772497070437377,
232
+ "groups": {
233
+ "Asian": {
234
+ "n": 143,
235
+ "fpr": 0.25,
236
+ "tpr": 0.8169014084507042,
237
+ "acc": 0.7832167832167832,
238
+ "dp": 0.5314685314685315
239
+ },
240
+ "Black": {
241
+ "n": 146,
242
+ "fpr": 0.17567567567567569,
243
+ "tpr": 0.8611111111111112,
244
+ "acc": 0.8424657534246576,
245
+ "dp": 0.5136986301369864
246
+ },
247
+ "Indian": {
248
+ "n": 145,
249
+ "fpr": 0.056338028169014086,
250
+ "tpr": 0.8918918918918919,
251
+ "acc": 0.9172413793103448,
252
+ "dp": 0.4827586206896552
253
+ },
254
+ "White": {
255
+ "n": 147,
256
+ "fpr": 0.1891891891891892,
257
+ "tpr": 0.863013698630137,
258
+ "acc": 0.8367346938775511,
259
+ "dp": 0.5238095238095238
260
+ }
261
+ }
262
+ },
263
+ "age_group": {
264
+ "F_FPR": 9.584439474572948,
265
+ "F_MEO": 31.25,
266
+ "F_DP": 4.933464365664702,
267
+ "F_OAE": 5.285015605545574,
268
+ "groups": {
269
+ "0-9": {
270
+ "n": 96,
271
+ "fpr": 0.041666666666666664,
272
+ "tpr": 0.8125,
273
+ "acc": 0.8854166666666666,
274
+ "dp": 0.4270833333333333
275
+ },
276
+ "10-19": {
277
+ "n": 97,
278
+ "fpr": 0.12244897959183673,
279
+ "tpr": 0.875,
280
+ "acc": 0.8762886597938144,
281
+ "dp": 0.4948453608247423
282
+ },
283
+ "20-29": {
284
+ "n": 96,
285
+ "fpr": 0.14583333333333334,
286
+ "tpr": 0.875,
287
+ "acc": 0.8645833333333334,
288
+ "dp": 0.5104166666666666
289
+ },
290
+ "30-39": {
291
+ "n": 98,
292
+ "fpr": 0.14285714285714285,
293
+ "tpr": 0.9183673469387755,
294
+ "acc": 0.8877551020408163,
295
+ "dp": 0.5306122448979592
296
+ },
297
+ "40-49": {
298
+ "n": 98,
299
+ "fpr": 0.20408163265306123,
300
+ "tpr": 0.8367346938775511,
301
+ "acc": 0.8163265306122449,
302
+ "dp": 0.5204081632653061
303
+ },
304
+ "50+": {
305
+ "n": 96,
306
+ "fpr": 0.3541666666666667,
307
+ "tpr": 0.8333333333333334,
308
+ "acc": 0.7395833333333334,
309
+ "dp": 0.59375
310
+ }
311
+ }
312
+ }
313
+ }
314
+ }
robustnessv2/runs.json ADDED
@@ -0,0 +1,638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "runs": [
3
+ {
4
+ "ckpt": "checkpoints/lipfd_train/model_epoch_5.pth",
5
+ "saved_at": "2026-06-25 21:26:12",
6
+ "load_info": {
7
+ "missing_count": 0,
8
+ "unexpected_count": 0
9
+ },
10
+ "real_list_path": "datasets/FairTalking-Bench/test/0_real",
11
+ "fake_list_path": "datasets/FairTalking-Bench/test/1_fake",
12
+ "demographics_csv": "/apdcephfs_gy4/share_303628665/joywu/research/test.csv",
13
+ "seed": 42,
14
+ "perturbation": "color_saturation",
15
+ "level": 2,
16
+ "param": 0.8,
17
+ "n_clips": 581,
18
+ "n_samples": 11610,
19
+ "overall_clip": {
20
+ "AUROC": 0.9336769759450173,
21
+ "AP": 0.9299403760888295,
22
+ "Accuracy@0.50": 0.8450946643717728,
23
+ "Confusion Matrix": [
24
+ [
25
+ 253,
26
+ 38
27
+ ],
28
+ [
29
+ 52,
30
+ 238
31
+ ]
32
+ ],
33
+ "Classification Report": {
34
+ "0": {
35
+ "precision": 0.8295081967213115,
36
+ "recall": 0.8694158075601375,
37
+ "f1-score": 0.8489932885906042,
38
+ "support": 291.0
39
+ },
40
+ "1": {
41
+ "precision": 0.8623188405797102,
42
+ "recall": 0.8206896551724138,
43
+ "f1-score": 0.8409893992932863,
44
+ "support": 290.0
45
+ },
46
+ "accuracy": 0.8450946643717728,
47
+ "macro avg": {
48
+ "precision": 0.8459135186505109,
49
+ "recall": 0.8450527313662757,
50
+ "f1-score": 0.8449913439419452,
51
+ "support": 581.0
52
+ },
53
+ "weighted avg": {
54
+ "precision": 0.8458852822960716,
55
+ "recall": 0.8450946643717728,
56
+ "f1-score": 0.8449982319706004,
57
+ "support": 581.0
58
+ }
59
+ },
60
+ "EER_threshold": 0.49212807714939116,
61
+ "Acc@EER": 0.8519793459552496,
62
+ "TPR@FPR=1%": 0.506896551724138,
63
+ "TPR@FPR=0.1%": 0.034482758620689655,
64
+ "Accuracy": 0.8450946643717728
65
+ },
66
+ "per_fake_vs_real": {
67
+ "EDTalk": {
68
+ "AUROC": 0.9378828626923652,
69
+ "AP": 0.8595528671515583,
70
+ "Accuracy@0.50": 0.8668407310704961,
71
+ "Confusion Matrix": [
72
+ [
73
+ 253,
74
+ 38
75
+ ],
76
+ [
77
+ 13,
78
+ 79
79
+ ]
80
+ ],
81
+ "Classification Report": {
82
+ "0": {
83
+ "precision": 0.9511278195488722,
84
+ "recall": 0.8694158075601375,
85
+ "f1-score": 0.9084380610412927,
86
+ "support": 291.0
87
+ },
88
+ "1": {
89
+ "precision": 0.6752136752136753,
90
+ "recall": 0.8586956521739131,
91
+ "f1-score": 0.7559808612440192,
92
+ "support": 92.0
93
+ },
94
+ "accuracy": 0.8668407310704961,
95
+ "macro avg": {
96
+ "precision": 0.8131707473812737,
97
+ "recall": 0.8640557298670253,
98
+ "f1-score": 0.8322094611426559,
99
+ "support": 383.0
100
+ },
101
+ "weighted avg": {
102
+ "precision": 0.8848507927111747,
103
+ "recall": 0.8668407310704961,
104
+ "f1-score": 0.8718164882440363,
105
+ "support": 383.0
106
+ }
107
+ },
108
+ "EER_threshold": 0.4876908928155899,
109
+ "Acc@EER": 0.8433420365535248,
110
+ "TPR@FPR=1%": 0.5760869565217391,
111
+ "TPR@FPR=0.1%": 0.06521739130434782,
112
+ "Accuracy": 0.8668407310704961
113
+ },
114
+ "Float": {
115
+ "AUROC": 0.9298506476341527,
116
+ "AP": 0.8253371406949079,
117
+ "Accuracy@0.50": 0.8430379746835444,
118
+ "Confusion Matrix": [
119
+ [
120
+ 253,
121
+ 38
122
+ ],
123
+ [
124
+ 24,
125
+ 80
126
+ ]
127
+ ],
128
+ "Classification Report": {
129
+ "0": {
130
+ "precision": 0.9133574007220217,
131
+ "recall": 0.8694158075601375,
132
+ "f1-score": 0.8908450704225351,
133
+ "support": 291.0
134
+ },
135
+ "1": {
136
+ "precision": 0.6779661016949152,
137
+ "recall": 0.7692307692307693,
138
+ "f1-score": 0.7207207207207208,
139
+ "support": 104.0
140
+ },
141
+ "accuracy": 0.8430379746835444,
142
+ "macro avg": {
143
+ "precision": 0.7956617512084685,
144
+ "recall": 0.8193232883954533,
145
+ "f1-score": 0.805782895571628,
146
+ "support": 395.0
147
+ },
148
+ "weighted avg": {
149
+ "precision": 0.851380957433872,
150
+ "recall": 0.8430379746835444,
151
+ "f1-score": 0.846052836576994,
152
+ "support": 395.0
153
+ }
154
+ },
155
+ "EER_threshold": 0.49075316786766054,
156
+ "Acc@EER": 0.8455696202531645,
157
+ "TPR@FPR=1%": 0.4519230769230769,
158
+ "TPR@FPR=0.1%": 0.028846153846153848,
159
+ "Accuracy": 0.8430379746835444
160
+ },
161
+ "SadTalk": {
162
+ "AUROC": 0.9337939606638883,
163
+ "AP": 0.8288933459986066,
164
+ "Accuracy@0.50": 0.8623376623376623,
165
+ "Confusion Matrix": [
166
+ [
167
+ 253,
168
+ 38
169
+ ],
170
+ [
171
+ 15,
172
+ 79
173
+ ]
174
+ ],
175
+ "Classification Report": {
176
+ "0": {
177
+ "precision": 0.9440298507462687,
178
+ "recall": 0.8694158075601375,
179
+ "f1-score": 0.9051878354203937,
180
+ "support": 291.0
181
+ },
182
+ "1": {
183
+ "precision": 0.6752136752136753,
184
+ "recall": 0.8404255319148937,
185
+ "f1-score": 0.7488151658767773,
186
+ "support": 94.0
187
+ },
188
+ "accuracy": 0.8623376623376623,
189
+ "macro avg": {
190
+ "precision": 0.809621762979972,
191
+ "recall": 0.8549206697375156,
192
+ "f1-score": 0.8270015006485856,
193
+ "support": 385.0
194
+ },
195
+ "weighted avg": {
196
+ "precision": 0.8783968104863626,
197
+ "recall": 0.8623376623376623,
198
+ "f1-score": 0.8670085342850693,
199
+ "support": 385.0
200
+ }
201
+ },
202
+ "EER_threshold": 0.49250459372997285,
203
+ "Acc@EER": 0.8597402597402597,
204
+ "TPR@FPR=1%": 0.5,
205
+ "TPR@FPR=0.1%": 0.010638297872340425,
206
+ "Accuracy": 0.8623376623376623
207
+ }
208
+ },
209
+ "fairness_overall": {
210
+ "gender": {
211
+ "F_FPR": 1.4194615021256505,
212
+ "F_MEO": 6.649543378995427,
213
+ "F_DP": 2.310755083661184,
214
+ "F_OAE": 0.9527420960326105,
215
+ "groups": {
216
+ "Female": {
217
+ "n": 289,
218
+ "fpr": 0.14482758620689656,
219
+ "tpr": 0.8541666666666666,
220
+ "acc": 0.8546712802768166,
221
+ "dp": 0.4982698961937716
222
+ },
223
+ "Male": {
224
+ "n": 292,
225
+ "fpr": 0.11643835616438356,
226
+ "tpr": 0.7876712328767124,
227
+ "acc": 0.8356164383561644,
228
+ "dp": 0.4520547945205479
229
+ }
230
+ }
231
+ },
232
+ "race4": {
233
+ "F_FPR": 4.878132134683478,
234
+ "F_MEO": 13.285116102017511,
235
+ "F_DP": 2.1747435496448455,
236
+ "F_OAE": 2.679472364199921,
237
+ "groups": {
238
+ "Asian": {
239
+ "n": 143,
240
+ "fpr": 0.1527777777777778,
241
+ "tpr": 0.8028169014084507,
242
+ "acc": 0.8251748251748252,
243
+ "dp": 0.4755244755244755
244
+ },
245
+ "Black": {
246
+ "n": 146,
247
+ "fpr": 0.12162162162162163,
248
+ "tpr": 0.8055555555555556,
249
+ "acc": 0.8424657534246576,
250
+ "dp": 0.4589041095890411
251
+ },
252
+ "Indian": {
253
+ "n": 145,
254
+ "fpr": 0.056338028169014086,
255
+ "tpr": 0.8378378378378378,
256
+ "acc": 0.8896551724137931,
257
+ "dp": 0.45517241379310347
258
+ },
259
+ "White": {
260
+ "n": 147,
261
+ "fpr": 0.1891891891891892,
262
+ "tpr": 0.8356164383561644,
263
+ "acc": 0.8231292517006803,
264
+ "dp": 0.5102040816326531
265
+ }
266
+ }
267
+ },
268
+ "age_group": {
269
+ "F_FPR": 8.981716988241686,
270
+ "F_MEO": 29.166666666666668,
271
+ "F_DP": 5.135692464910353,
272
+ "F_OAE": 4.948782010229553,
273
+ "groups": {
274
+ "0-9": {
275
+ "n": 96,
276
+ "fpr": 0.020833333333333332,
277
+ "tpr": 0.75,
278
+ "acc": 0.8645833333333334,
279
+ "dp": 0.3854166666666667
280
+ },
281
+ "10-19": {
282
+ "n": 97,
283
+ "fpr": 0.10204081632653061,
284
+ "tpr": 0.875,
285
+ "acc": 0.8865979381443299,
286
+ "dp": 0.4845360824742268
287
+ },
288
+ "20-29": {
289
+ "n": 96,
290
+ "fpr": 0.08333333333333333,
291
+ "tpr": 0.8333333333333334,
292
+ "acc": 0.875,
293
+ "dp": 0.4583333333333333
294
+ },
295
+ "30-39": {
296
+ "n": 98,
297
+ "fpr": 0.14285714285714285,
298
+ "tpr": 0.8775510204081632,
299
+ "acc": 0.8673469387755102,
300
+ "dp": 0.5102040816326531
301
+ },
302
+ "40-49": {
303
+ "n": 98,
304
+ "fpr": 0.12244897959183673,
305
+ "tpr": 0.7959183673469388,
306
+ "acc": 0.8367346938775511,
307
+ "dp": 0.45918367346938777
308
+ },
309
+ "50+": {
310
+ "n": 96,
311
+ "fpr": 0.3125,
312
+ "tpr": 0.7916666666666666,
313
+ "acc": 0.7395833333333334,
314
+ "dp": 0.5520833333333334
315
+ }
316
+ }
317
+ }
318
+ }
319
+ },
320
+ {
321
+ "ckpt": "checkpoints/lipfd_train/model_epoch_10.pth",
322
+ "saved_at": "2026-06-25 21:27:17",
323
+ "load_info": {
324
+ "missing_count": 0,
325
+ "unexpected_count": 0
326
+ },
327
+ "real_list_path": "datasets/FairTalking-Bench/test/0_real",
328
+ "fake_list_path": "datasets/FairTalking-Bench/test/1_fake",
329
+ "demographics_csv": "/apdcephfs_gy4/share_303628665/joywu/research/test.csv",
330
+ "seed": 42,
331
+ "perturbation": "gaussian_noise",
332
+ "level": 1,
333
+ "param": 0.0,
334
+ "n_clips": 581,
335
+ "n_samples": 11610,
336
+ "overall_clip": {
337
+ "AUROC": 0.9710036734210215,
338
+ "AP": 0.9624283772952034,
339
+ "Accuracy@0.50": 0.9053356282271945,
340
+ "Confusion Matrix": [
341
+ [
342
+ 250,
343
+ 41
344
+ ],
345
+ [
346
+ 14,
347
+ 276
348
+ ]
349
+ ],
350
+ "Classification Report": {
351
+ "0": {
352
+ "precision": 0.946969696969697,
353
+ "recall": 0.8591065292096219,
354
+ "f1-score": 0.900900900900901,
355
+ "support": 291.0
356
+ },
357
+ "1": {
358
+ "precision": 0.8706624605678234,
359
+ "recall": 0.9517241379310345,
360
+ "f1-score": 0.9093904448105437,
361
+ "support": 290.0
362
+ },
363
+ "accuracy": 0.9053356282271945,
364
+ "macro avg": {
365
+ "precision": 0.9088160787687602,
366
+ "recall": 0.9054153335703282,
367
+ "f1-score": 0.9051456728557223,
368
+ "support": 581.0
369
+ },
370
+ "weighted avg": {
371
+ "precision": 0.908881747646903,
372
+ "recall": 0.9053356282271945,
373
+ "f1-score": 0.9051383668798965,
374
+ "support": 581.0
375
+ }
376
+ },
377
+ "EER_threshold": 0.5720391809940338,
378
+ "Acc@EER": 0.919104991394148,
379
+ "TPR@FPR=1%": 0.6103448275862069,
380
+ "TPR@FPR=0.1%": 0.09310344827586207,
381
+ "Accuracy": 0.9053356282271945
382
+ },
383
+ "per_fake_vs_real": {
384
+ "EDTalk": {
385
+ "AUROC": 0.9696324518153294,
386
+ "AP": 0.8995520129228476,
387
+ "Accuracy@0.50": 0.8798955613577023,
388
+ "Confusion Matrix": [
389
+ [
390
+ 250,
391
+ 41
392
+ ],
393
+ [
394
+ 5,
395
+ 87
396
+ ]
397
+ ],
398
+ "Classification Report": {
399
+ "0": {
400
+ "precision": 0.9803921568627451,
401
+ "recall": 0.8591065292096219,
402
+ "f1-score": 0.9157509157509157,
403
+ "support": 291.0
404
+ },
405
+ "1": {
406
+ "precision": 0.6796875,
407
+ "recall": 0.9456521739130435,
408
+ "f1-score": 0.7909090909090909,
409
+ "support": 92.0
410
+ },
411
+ "accuracy": 0.8798955613577023,
412
+ "macro avg": {
413
+ "precision": 0.8300398284313726,
414
+ "recall": 0.9023793515613328,
415
+ "f1-score": 0.8533300033300033,
416
+ "support": 383.0
417
+ },
418
+ "weighted avg": {
419
+ "precision": 0.9081602288434956,
420
+ "recall": 0.8798955613577023,
421
+ "f1-score": 0.885762801167501,
422
+ "support": 383.0
423
+ }
424
+ },
425
+ "EER_threshold": 0.5730031251907348,
426
+ "Acc@EER": 0.9216710182767625,
427
+ "TPR@FPR=1%": 0.6304347826086957,
428
+ "TPR@FPR=0.1%": 0.09782608695652174,
429
+ "Accuracy": 0.8798955613577023
430
+ },
431
+ "Float": {
432
+ "AUROC": 0.9705921226539783,
433
+ "AP": 0.9096209876444205,
434
+ "Accuracy@0.50": 0.8810126582278481,
435
+ "Confusion Matrix": [
436
+ [
437
+ 250,
438
+ 41
439
+ ],
440
+ [
441
+ 6,
442
+ 98
443
+ ]
444
+ ],
445
+ "Classification Report": {
446
+ "0": {
447
+ "precision": 0.9765625,
448
+ "recall": 0.8591065292096219,
449
+ "f1-score": 0.9140767824497257,
450
+ "support": 291.0
451
+ },
452
+ "1": {
453
+ "precision": 0.7050359712230215,
454
+ "recall": 0.9423076923076923,
455
+ "f1-score": 0.8065843621399178,
456
+ "support": 104.0
457
+ },
458
+ "accuracy": 0.8810126582278481,
459
+ "macro avg": {
460
+ "precision": 0.8407992356115108,
461
+ "recall": 0.9007071107586571,
462
+ "f1-score": 0.8603305722948218,
463
+ "support": 395.0
464
+ },
465
+ "weighted avg": {
466
+ "precision": 0.9050719709042893,
467
+ "recall": 0.8810126582278481,
468
+ "f1-score": 0.8857749806466372,
469
+ "support": 395.0
470
+ }
471
+ },
472
+ "EER_threshold": 0.5760782033205032,
473
+ "Acc@EER": 0.9240506329113924,
474
+ "TPR@FPR=1%": 0.5769230769230769,
475
+ "TPR@FPR=0.1%": 0.10576923076923077,
476
+ "Accuracy": 0.8810126582278481
477
+ },
478
+ "SadTalk": {
479
+ "AUROC": 0.9728010528624699,
480
+ "AP": 0.899161539979738,
481
+ "Accuracy@0.50": 0.8857142857142857,
482
+ "Confusion Matrix": [
483
+ [
484
+ 250,
485
+ 41
486
+ ],
487
+ [
488
+ 3,
489
+ 91
490
+ ]
491
+ ],
492
+ "Classification Report": {
493
+ "0": {
494
+ "precision": 0.9881422924901185,
495
+ "recall": 0.8591065292096219,
496
+ "f1-score": 0.9191176470588235,
497
+ "support": 291.0
498
+ },
499
+ "1": {
500
+ "precision": 0.6893939393939394,
501
+ "recall": 0.9680851063829787,
502
+ "f1-score": 0.8053097345132745,
503
+ "support": 94.0
504
+ },
505
+ "accuracy": 0.8857142857142857,
506
+ "macro avg": {
507
+ "precision": 0.838768115942029,
508
+ "recall": 0.9135958177963004,
509
+ "f1-score": 0.8622136907860489,
510
+ "support": 385.0
511
+ },
512
+ "weighted avg": {
513
+ "precision": 0.9152011361497527,
514
+ "recall": 0.8857142857142857,
515
+ "f1-score": 0.8913307800996504,
516
+ "support": 385.0
517
+ }
518
+ },
519
+ "EER_threshold": 0.5509923934936524,
520
+ "Acc@EER": 0.9090909090909091,
521
+ "TPR@FPR=1%": 0.6276595744680851,
522
+ "TPR@FPR=0.1%": 0.07446808510638298,
523
+ "Accuracy": 0.8857142857142857
524
+ }
525
+ },
526
+ "fairness_overall": {
527
+ "gender": {
528
+ "F_FPR": 2.4539442607463395,
529
+ "F_MEO": 4.907888521492679,
530
+ "F_DP": 1.142342513153527,
531
+ "F_OAE": 1.2537327582120672,
532
+ "groups": {
533
+ "Female": {
534
+ "n": 289,
535
+ "fpr": 0.16551724137931034,
536
+ "tpr": 0.9513888888888888,
537
+ "acc": 0.8927335640138409,
538
+ "dp": 0.5570934256055363
539
+ },
540
+ "Male": {
541
+ "n": 292,
542
+ "fpr": 0.11643835616438356,
543
+ "tpr": 0.952054794520548,
544
+ "acc": 0.9178082191780822,
545
+ "dp": 0.5342465753424658
546
+ }
547
+ }
548
+ },
549
+ "race4": {
550
+ "F_FPR": 5.130508985141023,
551
+ "F_MEO": 13.810641627543035,
552
+ "F_DP": 1.991767150590385,
553
+ "F_OAE": 3.099992139753374,
554
+ "groups": {
555
+ "Asian": {
556
+ "n": 143,
557
+ "fpr": 0.19444444444444445,
558
+ "tpr": 0.9295774647887324,
559
+ "acc": 0.8671328671328671,
560
+ "dp": 0.5594405594405595
561
+ },
562
+ "Black": {
563
+ "n": 146,
564
+ "fpr": 0.16216216216216217,
565
+ "tpr": 0.9861111111111112,
566
+ "acc": 0.910958904109589,
567
+ "dp": 0.5684931506849316
568
+ },
569
+ "Indian": {
570
+ "n": 145,
571
+ "fpr": 0.056338028169014086,
572
+ "tpr": 0.9594594594594594,
573
+ "acc": 0.9517241379310345,
574
+ "dp": 0.5172413793103449
575
+ },
576
+ "White": {
577
+ "n": 147,
578
+ "fpr": 0.14864864864864866,
579
+ "tpr": 0.9315068493150684,
580
+ "acc": 0.891156462585034,
581
+ "dp": 0.5374149659863946
582
+ }
583
+ }
584
+ },
585
+ "age_group": {
586
+ "F_FPR": 9.972494132228265,
587
+ "F_MEO": 29.29421768707483,
588
+ "F_DP": 5.911077463330453,
589
+ "F_OAE": 4.3314141493955916,
590
+ "groups": {
591
+ "0-9": {
592
+ "n": 96,
593
+ "fpr": 0.0625,
594
+ "tpr": 0.8958333333333334,
595
+ "acc": 0.9166666666666666,
596
+ "dp": 0.4791666666666667
597
+ },
598
+ "10-19": {
599
+ "n": 97,
600
+ "fpr": 0.061224489795918366,
601
+ "tpr": 0.9583333333333334,
602
+ "acc": 0.9484536082474226,
603
+ "dp": 0.5051546391752577
604
+ },
605
+ "20-29": {
606
+ "n": 96,
607
+ "fpr": 0.10416666666666667,
608
+ "tpr": 0.9583333333333334,
609
+ "acc": 0.9270833333333334,
610
+ "dp": 0.53125
611
+ },
612
+ "30-39": {
613
+ "n": 98,
614
+ "fpr": 0.12244897959183673,
615
+ "tpr": 0.9591836734693877,
616
+ "acc": 0.9183673469387755,
617
+ "dp": 0.5408163265306123
618
+ },
619
+ "40-49": {
620
+ "n": 98,
621
+ "fpr": 0.14285714285714285,
622
+ "tpr": 0.9591836734693877,
623
+ "acc": 0.9081632653061225,
624
+ "dp": 0.5510204081632653
625
+ },
626
+ "50+": {
627
+ "n": 96,
628
+ "fpr": 0.3541666666666667,
629
+ "tpr": 0.9791666666666666,
630
+ "acc": 0.8125,
631
+ "dp": 0.6666666666666666
632
+ }
633
+ }
634
+ }
635
+ }
636
+ }
637
+ ]
638
+ }
robustnessv2/runs.json.20260625_212207.bak ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "runs": [
3
+ {
4
+ "ckpt": "checkpoints/lipfd_train/model_epoch_5.pth",
5
+ "saved_at": "2026-06-25 21:20:39",
6
+ "load_info": {
7
+ "missing_count": 0,
8
+ "unexpected_count": 0
9
+ },
10
+ "real_list_path": "datasets/FairTalking-Bench/test/0_real",
11
+ "fake_list_path": "datasets/FairTalking-Bench/test/1_fake",
12
+ "demographics_csv": "/apdcephfs_gy4/share_303628665/joywu/research/test.csv",
13
+ "seed": 42,
14
+ "perturbation": "gaussian_noise",
15
+ "level": 1,
16
+ "param": 0.0,
17
+ "n_clips": 581,
18
+ "n_samples": 11610,
19
+ "overall_clip": {
20
+ "AUROC": 0.9333807323142551,
21
+ "AP": 0.9327153892461657,
22
+ "Accuracy@0.50": 0.8450946643717728,
23
+ "Confusion Matrix": [
24
+ [
25
+ 242,
26
+ 49
27
+ ],
28
+ [
29
+ 41,
30
+ 249
31
+ ]
32
+ ],
33
+ "Classification Report": {
34
+ "0": {
35
+ "precision": 0.8551236749116607,
36
+ "recall": 0.8316151202749141,
37
+ "f1-score": 0.843205574912892,
38
+ "support": 291.0
39
+ },
40
+ "1": {
41
+ "precision": 0.8355704697986577,
42
+ "recall": 0.8586206896551725,
43
+ "f1-score": 0.8469387755102041,
44
+ "support": 290.0
45
+ },
46
+ "accuracy": 0.8450946643717728,
47
+ "macro avg": {
48
+ "precision": 0.8453470723551593,
49
+ "recall": 0.8451179049650432,
50
+ "f1-score": 0.8450721752115481,
51
+ "support": 581.0
52
+ },
53
+ "weighted avg": {
54
+ "precision": 0.8453638995540517,
55
+ "recall": 0.8450946643717728,
56
+ "f1-score": 0.8450689624743731,
57
+ "support": 581.0
58
+ }
59
+ },
60
+ "EER_threshold": 0.5060416251420975,
61
+ "Acc@EER": 0.8433734939759037,
62
+ "TPR@FPR=1%": 0.5137931034482759,
63
+ "TPR@FPR=0.1%": 0.0896551724137931,
64
+ "Accuracy": 0.8450946643717728
65
+ },
66
+ "per_fake_vs_real": {
67
+ "EDTalk": {
68
+ "AUROC": 0.9378828626923652,
69
+ "AP": 0.8637361754335757,
70
+ "Accuracy@0.50": 0.8407310704960835,
71
+ "Confusion Matrix": [
72
+ [
73
+ 242,
74
+ 49
75
+ ],
76
+ [
77
+ 12,
78
+ 80
79
+ ]
80
+ ],
81
+ "Classification Report": {
82
+ "0": {
83
+ "precision": 0.952755905511811,
84
+ "recall": 0.8316151202749141,
85
+ "f1-score": 0.8880733944954128,
86
+ "support": 291.0
87
+ },
88
+ "1": {
89
+ "precision": 0.6201550387596899,
90
+ "recall": 0.8695652173913043,
91
+ "f1-score": 0.7239819004524886,
92
+ "support": 92.0
93
+ },
94
+ "accuracy": 0.8407310704960835,
95
+ "macro avg": {
96
+ "precision": 0.7864554721357504,
97
+ "recall": 0.8505901688331092,
98
+ "f1-score": 0.8060276474739507,
99
+ "support": 383.0
100
+ },
101
+ "weighted avg": {
102
+ "precision": 0.8728622247254006,
103
+ "recall": 0.8407310704960835,
104
+ "f1-score": 0.8486571609394101,
105
+ "support": 383.0
106
+ }
107
+ },
108
+ "EER_threshold": 0.5170380979776382,
109
+ "Acc@EER": 0.8746736292428199,
110
+ "TPR@FPR=1%": 0.5760869565217391,
111
+ "TPR@FPR=0.1%": 0.10869565217391304,
112
+ "Accuracy": 0.8407310704960835
113
+ },
114
+ "Float": {
115
+ "AUROC": 0.9278680941052074,
116
+ "AP": 0.8317222383016976,
117
+ "Accuracy@0.50": 0.8354430379746836,
118
+ "Confusion Matrix": [
119
+ [
120
+ 242,
121
+ 49
122
+ ],
123
+ [
124
+ 16,
125
+ 88
126
+ ]
127
+ ],
128
+ "Classification Report": {
129
+ "0": {
130
+ "precision": 0.937984496124031,
131
+ "recall": 0.8316151202749141,
132
+ "f1-score": 0.8816029143897997,
133
+ "support": 291.0
134
+ },
135
+ "1": {
136
+ "precision": 0.6423357664233577,
137
+ "recall": 0.8461538461538461,
138
+ "f1-score": 0.7302904564315352,
139
+ "support": 104.0
140
+ },
141
+ "accuracy": 0.8354430379746836,
142
+ "macro avg": {
143
+ "precision": 0.7901601312736943,
144
+ "recall": 0.8388844832143801,
145
+ "f1-score": 0.8059466854106674,
146
+ "support": 395.0
147
+ },
148
+ "weighted avg": {
149
+ "precision": 0.8601428052661323,
150
+ "recall": 0.8354430379746836,
151
+ "f1-score": 0.841763684952687,
152
+ "support": 395.0
153
+ }
154
+ },
155
+ "EER_threshold": 0.5007072478532791,
156
+ "Acc@EER": 0.8379746835443038,
157
+ "TPR@FPR=1%": 0.46153846153846156,
158
+ "TPR@FPR=0.1%": 0.07692307692307693,
159
+ "Accuracy": 0.8354430379746836
160
+ },
161
+ "SadTalk": {
162
+ "AUROC": 0.9350734810265409,
163
+ "AP": 0.8440944635739278,
164
+ "Accuracy@0.50": 0.8389610389610389,
165
+ "Confusion Matrix": [
166
+ [
167
+ 242,
168
+ 49
169
+ ],
170
+ [
171
+ 13,
172
+ 81
173
+ ]
174
+ ],
175
+ "Classification Report": {
176
+ "0": {
177
+ "precision": 0.9490196078431372,
178
+ "recall": 0.8316151202749141,
179
+ "f1-score": 0.8864468864468865,
180
+ "support": 291.0
181
+ },
182
+ "1": {
183
+ "precision": 0.6230769230769231,
184
+ "recall": 0.8617021276595744,
185
+ "f1-score": 0.7232142857142857,
186
+ "support": 94.0
187
+ },
188
+ "accuracy": 0.8389610389610389,
189
+ "macro avg": {
190
+ "precision": 0.7860482654600301,
191
+ "recall": 0.8466586239672442,
192
+ "f1-score": 0.8048305860805861,
193
+ "support": 385.0
194
+ },
195
+ "weighted avg": {
196
+ "precision": 0.86943879649762,
197
+ "recall": 0.8389610389610389,
198
+ "f1-score": 0.8465926930212644,
199
+ "support": 385.0
200
+ }
201
+ },
202
+ "EER_threshold": 0.5093957483768463,
203
+ "Acc@EER": 0.8519480519480519,
204
+ "TPR@FPR=1%": 0.5106382978723404,
205
+ "TPR@FPR=0.1%": 0.0851063829787234,
206
+ "Accuracy": 0.8389610389610389
207
+ }
208
+ },
209
+ "fairness_overall": {
210
+ "gender": {
211
+ "F_FPR": 1.776098252243742,
212
+ "F_MEO": 3.552196504487484,
213
+ "F_DP": 1.297577854671278,
214
+ "F_OAE": 0.42423093330805073,
215
+ "groups": {
216
+ "Female": {
217
+ "n": 289,
218
+ "fpr": 0.18620689655172415,
219
+ "tpr": 0.8680555555555556,
220
+ "acc": 0.8408304498269896,
221
+ "dp": 0.5259515570934256
222
+ },
223
+ "Male": {
224
+ "n": 292,
225
+ "fpr": 0.1506849315068493,
226
+ "tpr": 0.8493150684931506,
227
+ "acc": 0.8493150684931506,
228
+ "dp": 0.5
229
+ }
230
+ }
231
+ },
232
+ "race4": {
233
+ "F_FPR": 7.01785844183937,
234
+ "F_MEO": 19.366197183098592,
235
+ "F_DP": 1.852662982397705,
236
+ "F_OAE": 4.772497070437377,
237
+ "groups": {
238
+ "Asian": {
239
+ "n": 143,
240
+ "fpr": 0.25,
241
+ "tpr": 0.8169014084507042,
242
+ "acc": 0.7832167832167832,
243
+ "dp": 0.5314685314685315
244
+ },
245
+ "Black": {
246
+ "n": 146,
247
+ "fpr": 0.17567567567567569,
248
+ "tpr": 0.8611111111111112,
249
+ "acc": 0.8424657534246576,
250
+ "dp": 0.5136986301369864
251
+ },
252
+ "Indian": {
253
+ "n": 145,
254
+ "fpr": 0.056338028169014086,
255
+ "tpr": 0.8918918918918919,
256
+ "acc": 0.9172413793103448,
257
+ "dp": 0.4827586206896552
258
+ },
259
+ "White": {
260
+ "n": 147,
261
+ "fpr": 0.1891891891891892,
262
+ "tpr": 0.863013698630137,
263
+ "acc": 0.8367346938775511,
264
+ "dp": 0.5238095238095238
265
+ }
266
+ }
267
+ },
268
+ "age_group": {
269
+ "F_FPR": 9.584439474572948,
270
+ "F_MEO": 31.25,
271
+ "F_DP": 4.933464365664702,
272
+ "F_OAE": 5.285015605545574,
273
+ "groups": {
274
+ "0-9": {
275
+ "n": 96,
276
+ "fpr": 0.041666666666666664,
277
+ "tpr": 0.8125,
278
+ "acc": 0.8854166666666666,
279
+ "dp": 0.4270833333333333
280
+ },
281
+ "10-19": {
282
+ "n": 97,
283
+ "fpr": 0.12244897959183673,
284
+ "tpr": 0.875,
285
+ "acc": 0.8762886597938144,
286
+ "dp": 0.4948453608247423
287
+ },
288
+ "20-29": {
289
+ "n": 96,
290
+ "fpr": 0.14583333333333334,
291
+ "tpr": 0.875,
292
+ "acc": 0.8645833333333334,
293
+ "dp": 0.5104166666666666
294
+ },
295
+ "30-39": {
296
+ "n": 98,
297
+ "fpr": 0.14285714285714285,
298
+ "tpr": 0.9183673469387755,
299
+ "acc": 0.8877551020408163,
300
+ "dp": 0.5306122448979592
301
+ },
302
+ "40-49": {
303
+ "n": 98,
304
+ "fpr": 0.20408163265306123,
305
+ "tpr": 0.8367346938775511,
306
+ "acc": 0.8163265306122449,
307
+ "dp": 0.5204081632653061
308
+ },
309
+ "50+": {
310
+ "n": 96,
311
+ "fpr": 0.3541666666666667,
312
+ "tpr": 0.8333333333333334,
313
+ "acc": 0.7395833333333334,
314
+ "dp": 0.59375
315
+ }
316
+ }
317
+ }
318
+ }
319
+ }
320
+ ]
321
+ }
robustnessv4/robustness_table.csv ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ perturbation,level,param,n_clips,AUROC,AP,Accuracy,Acc@EER,TPR@FPR=1%,TPR@FPR=0.1%
2
+ block_wise,2,8,581,0.9706363313188766,0.961842625956055,0.9087779690189329,0.9173838209982789,0.596551724137931,0.09310344827586207
3
+ block_wise,3,16,581,0.9706244815736462,0.9616343179834019,0.9036144578313253,0.9173838209982789,0.5758620689655173,0.06896551724137931
4
+ block_wise,4,24,581,0.9684322787060078,0.9601029786120157,0.8967297762478486,0.9104991394148021,0.5793103448275863,0.07931034482758621
5
+ block_wise,5,32,581,0.9685744756487735,0.9606156625435756,0.9070567986230637,0.9156626506024096,0.5551724137931034,0.10344827586206896
6
+ color_contrast,2,0.85,581,0.9703400876881146,0.9618131893858384,0.8984509466437177,0.9208261617900172,0.503448275862069,0.07931034482758621
7
+ color_contrast,3,1.2,581,0.9726981869889797,0.9663464125394221,0.8967297762478486,0.9122203098106713,0.596551724137931,0.05517241379310345
8
+ color_contrast,4,1.4,581,0.9721649484536082,0.9677725431587463,0.891566265060241,0.9139414802065404,0.5379310344827586,0.12413793103448276
9
+ color_contrast,5,1.6,581,0.9712643678160919,0.969733587406969,0.8812392426850258,0.9139414802065404,0.6344827586206897,0.23448275862068965
10
+ color_saturation,2,0.8,581,0.9709325749496386,0.9625726687169951,0.9104991394148021,0.919104991394148,0.5827586206896552,0.06551724137931035
11
+ color_saturation,3,1.2,581,0.9710866216376348,0.9644582868698658,0.8950086058519794,0.9139414802065404,0.5793103448275863,0.13793103448275862
12
+ color_saturation,4,1.5,581,0.9706363313188766,0.9678130998911674,0.8881239242685026,0.9036144578313253,0.5310344827586206,0.2896551724137931
13
+ color_saturation,5,2.0,581,0.9643322668562626,0.9659882006624247,0.8640275387263339,0.8967297762478486,0.5862068965517241,0.5482758620689655
14
+ gaussian_blur,2,3,581,0.9700793932930442,0.9616367530805014,0.9053356282271945,0.9173838209982789,0.5862068965517241,0.09310344827586207
15
+ gaussian_blur,3,7,581,0.9657779357743809,0.9599197695711028,0.9036144578313253,0.9070567986230637,0.5103448275862069,0.1310344827586207
16
+ gaussian_blur,4,11,581,0.960149306789904,0.9546642897795196,0.8777969018932874,0.8967297762478486,0.4724137931034483,0.12758620689655173
17
+ gaussian_blur,5,15,581,0.9516174902239602,0.947260960348703,0.810671256454389,0.8881239242685026,0.41379310344827586,0.1310344827586207
18
+ gaussian_noise,1,0.0,581,0.9711695698542482,0.963284813670888,0.9070567986230637,0.919104991394148,0.6103448275862069,0.10344827586206896
19
+ gaussian_noise,2,0.001,581,0.9589998815025477,0.9546247005388946,0.8760757314974182,0.8967297762478486,0.3758620689655172,0.2655172413793103
20
+ gaussian_noise,3,0.005,581,0.9300628036497215,0.9246039218517703,0.8347676419965576,0.8519793459552496,0.3137931034482759,0.16896551724137931
21
+ gaussian_noise,4,0.01,581,0.9182723071453963,0.9116952521947262,0.7676419965576592,0.8450946643717728,0.2,0.05862068965517241
22
+ gaussian_noise,5,0.05,581,0.7283445905913023,0.7018203772621896,0.5008605851979346,0.6764199655765921,0.05862068965517241,0.034482758620689655
23
+ jpeg_quality,2,85,581,0.9713828652683967,0.9640729017480663,0.9053356282271945,0.919104991394148,0.6068965517241379,0.09655172413793103
24
+ jpeg_quality,3,70,581,0.9711103211280957,0.9635534900234138,0.9053356282271945,0.9173838209982789,0.6068965517241379,0.10689655172413794
25
+ jpeg_quality,4,50,581,0.971015523166252,0.9622118164633725,0.9053356282271945,0.9208261617900172,0.6137931034482759,0.07241379310344828
26
+ jpeg_quality,5,30,581,0.9702571394715014,0.9600982030270745,0.9018932874354562,0.9139414802065404,0.5793103448275863,0.05862068965517241
27
+ pixelate,2,2,581,0.9672710036734209,0.9609417769511195,0.9036144578313253,0.9104991394148021,0.5310344827586206,0.12413793103448276
28
+ pixelate,3,4,581,0.9586206896551723,0.9525942217545772,0.8657487091222031,0.8932874354561101,0.4586206896551724,0.09655172413793103
29
+ pixelate,4,6,581,0.9445194928309042,0.9409031038006339,0.7521514629948365,0.8657487091222031,0.3758620689655172,0.15172413793103448
30
+ pixelate,5,8,581,0.9223012205237587,0.9204455559793818,0.621342512908778,0.8313253012048193,0.29310344827586204,0.23448275862068965
robustnessv4/runs.json ADDED
The diff for this file is too large to render. See raw diff
 
robustnessv4/sweep.log ADDED
The diff for this file is too large to render. See raw diff
 
run_preprocess.sh ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # FT_work 数据集预处理快速开始脚本
4
+
5
+ echo "=========================================="
6
+ echo "FT_work 数据集预处理流程"
7
+ echo "=========================================="
8
+
9
+ # 步骤 1: 转换数据集格式
10
+ echo ""
11
+ echo "步骤 1/3: 转换数据集格式"
12
+ echo "将 FT_work 格式转换为 AVLips 格式..."
13
+ python convert_ft_work.py
14
+
15
+ if [ $? -ne 0 ]; then
16
+ echo "错误: 数据集转换失败!"
17
+ exit 1
18
+ fi
19
+
20
+ echo "✓ 数据集转换完成"
21
+ echo ""
22
+
23
+ # 步骤 2: 检查转换结果
24
+ echo "步骤 2/3: 检查转换结果"
25
+ echo "检查 AVLips 目录结构..."
26
+
27
+ if [ ! -d "./AVLips" ]; then
28
+ echo "错误: AVLips 目录不存在!"
29
+ exit 1
30
+ fi
31
+
32
+ real_count=$(ls -1 ./AVLips/0_real/*.mp4 2>/dev/null | wc -l)
33
+ fake_count=$(ls -1 ./AVLips/1_fake/*.mp4 2>/dev/null | wc -l)
34
+ real_audio_count=$(ls -1 ./AVLips/wav/0_real/*.wav 2>/dev/null | wc -l)
35
+ fake_audio_count=$(ls -1 ./AVLips/wav/1_fake/*.wav 2>/dev/null | wc -l)
36
+
37
+ echo " 真实视频: $real_count 个"
38
+ echo " 假视频: $fake_count 个"
39
+ echo " 真实音频: $real_audio_count 个"
40
+ echo " 假音频: $fake_audio_count 个"
41
+ echo ""
42
+
43
+ # 步骤 3: 运行预处理
44
+ echo "步骤 3/3: 运行预处理"
45
+ echo "开始提取帧和生成频谱图..."
46
+ echo ""
47
+
48
+ # 你可以选择使用原版或改进版
49
+ # 原版: python preprocess.py
50
+ # 改进版: python preprocess_improved.py
51
+
52
+ python preprocess_improved.py
53
+
54
+ if [ $? -ne 0 ]; then
55
+ echo "错误: 预处理失败!"
56
+ exit 1
57
+ fi
58
+
59
+ echo ""
60
+ echo "=========================================="
61
+ echo "✓ 全部完成!"
62
+ echo "=========================================="
63
+ echo ""
64
+ echo "输出目录: ./datasets/AVLips"
65
+ echo " - 真实样本: ./datasets/AVLips/0_real/"
66
+ echo " - 假样本: ./datasets/AVLips/1_fake/"
67
+ echo ""
run_robustness.sh ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # run_robustness.sh — sweep all 7 perturbations × 5 levels on the LipFD test set.
3
+ #
4
+ # Note: level=1 is a no-op for every perturbation in SEVERITY, so we only run
5
+ # it once (under "gaussian_noise") and treat that as the clean baseline. The
6
+ # runs.json output appends one entry per (perturbation, level) call.
7
+
8
+ set -e
9
+ cd /apdcephfs_gy4/share_303628665/joywu/research/LipFD
10
+
11
+ PYTHON=/opt/conda/envs/LipFD/bin/python
12
+ CKPT=checkpoints/lipfd_train/model_epoch_44.pth
13
+ REAL=datasets/FairTalking-Bench/test/0_real
14
+ FAKE=datasets/FairTalking-Bench/test/1_fake
15
+ CSV=/apdcephfs_gy4/share_303628665/joywu/research/test.csv
16
+ OUT_DIR=/apdcephfs_gy4/share_303628665/joywu/research/LipFD/robustness
17
+ JSON=$OUT_DIR/runs.json
18
+
19
+ mkdir -p "$OUT_DIR"
20
+
21
+ PERTURBATIONS=(color_saturation color_contrast block_wise gaussian_noise gaussian_blur pixelate jpeg_quality)
22
+ GPU=${GPU:-0}
23
+ BATCH=${BATCH:-16}
24
+ WORKERS=${WORKERS:-4}
25
+
26
+ # Clean any prior runs.json so this sweep is self-contained.
27
+ if [ -f "$JSON" ]; then
28
+ mv "$JSON" "${JSON}.$(date +%Y%m%d_%H%M%S).bak"
29
+ fi
30
+
31
+ # Single clean baseline (level=1 of any perturbation is no-op).
32
+ echo "===== baseline (no-op, level=1) ====="
33
+ $PYTHON evaluate_robustness.py \
34
+ --real_list_path "$REAL" --fake_list_path "$FAKE" \
35
+ --ckpt "$CKPT" --demographics_csv "$CSV" \
36
+ --perturbation gaussian_noise --level 1 \
37
+ --batch_size $BATCH --loader_workers $WORKERS --gpu $GPU \
38
+ --save_json "$JSON"
39
+
40
+ # Sweep level 2..5 for every perturbation.
41
+ for P in "${PERTURBATIONS[@]}"; do
42
+ for L in 2 3 4 5; do
43
+ echo "===== $P level=$L ====="
44
+ $PYTHON evaluate_robustness.py \
45
+ --real_list_path "$REAL" --fake_list_path "$FAKE" \
46
+ --ckpt "$CKPT" --demographics_csv "$CSV" \
47
+ --perturbation "$P" --level $L \
48
+ --batch_size $BATCH --loader_workers $WORKERS --gpu $GPU \
49
+ --save_json "$JSON"
50
+ done
51
+ done
52
+
53
+ echo
54
+ echo ">>> Sweep done. Results: $JSON"
run_robustness_v4.sh ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # run_robustness_v4.sh — sweep all 7 perturbations × 5 levels with the
3
+ # 5-crop-bug-fixed pipeline (see data/datasets.py:64 + evaluate_robustness.py).
4
+ #
5
+ # Same ckpt as v3 (model_epoch_10.pth) so v3 vs v4 isolates the bug fix.
6
+
7
+ set -e
8
+ cd /apdcephfs_gy4/share_303628665/joywu/research/LipFD
9
+
10
+ PYTHON=/opt/conda/envs/LipFD/bin/python
11
+ CKPT=checkpoints/lipfd_train/model_epoch_10.pth
12
+ REAL=datasets/FairTalking-Bench/test/0_real
13
+ FAKE=datasets/FairTalking-Bench/test/1_fake
14
+ CSV=/apdcephfs_gy4/share_303628665/joywu/research/test.csv
15
+ OUT_DIR=/apdcephfs_gy4/share_303628665/joywu/research/LipFD/robustnessv4
16
+ JSON=$OUT_DIR/runs.json
17
+
18
+ mkdir -p "$OUT_DIR"
19
+
20
+ PERTURBATIONS=(color_saturation color_contrast block_wise gaussian_noise gaussian_blur pixelate jpeg_quality)
21
+ GPU=${GPU:-2}
22
+ BATCH=${BATCH:-32}
23
+ WORKERS=${WORKERS:-8}
24
+
25
+ if [ -f "$JSON" ]; then
26
+ mv "$JSON" "${JSON}.$(date +%Y%m%d_%H%M%S).bak"
27
+ fi
28
+
29
+ echo "===== baseline (no-op, level=1) ====="
30
+ $PYTHON evaluate_robustness.py \
31
+ --real_list_path "$REAL" --fake_list_path "$FAKE" \
32
+ --ckpt "$CKPT" --demographics_csv "$CSV" \
33
+ --perturbation gaussian_noise --level 1 \
34
+ --batch_size $BATCH --loader_workers $WORKERS --gpu $GPU \
35
+ --save_json "$JSON"
36
+
37
+ for P in "${PERTURBATIONS[@]}"; do
38
+ for L in 2 3 4 5; do
39
+ echo "===== $P level=$L ====="
40
+ $PYTHON evaluate_robustness.py \
41
+ --real_list_path "$REAL" --fake_list_path "$FAKE" \
42
+ --ckpt "$CKPT" --demographics_csv "$CSV" \
43
+ --perturbation "$P" --level $L \
44
+ --batch_size $BATCH --loader_workers $WORKERS --gpu $GPU \
45
+ --save_json "$JSON"
46
+ done
47
+ done
48
+
49
+ echo
50
+ echo ">>> Sweep done. Results: $JSON"
run_robustnessv2.sh ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # run_robustness.sh — sweep all 7 perturbations × 5 levels on the LipFD test set.
3
+ #
4
+ # Note: level=1 is a no-op for every perturbation in SEVERITY, so we only run
5
+ # it once (under "gaussian_noise") and treat that as the clean baseline. The
6
+ # runs.json output appends one entry per (perturbation, level) call.
7
+
8
+ set -e
9
+ cd /apdcephfs_gy4/share_303628665/joywu/research/LipFD
10
+
11
+ PYTHON=/opt/conda/envs/LipFD/bin/python
12
+ CKPT=checkpoints/lipfd_train/model_epoch_10.pth
13
+ REAL=datasets/FairTalking-Bench/test/0_real
14
+ FAKE=datasets/FairTalking-Bench/test/1_fake
15
+ CSV=/apdcephfs_gy4/share_303628665/joywu/research/test.csv
16
+ OUT_DIR=/apdcephfs_gy4/share_303628665/joywu/research/LipFD/robustnessv3
17
+ JSON=$OUT_DIR/runs.json
18
+
19
+ mkdir -p "$OUT_DIR"
20
+
21
+ PERTURBATIONS=(color_saturation color_contrast block_wise gaussian_noise gaussian_blur pixelate jpeg_quality)
22
+ GPU=${GPU:-0}
23
+ BATCH=${BATCH:-16}
24
+ WORKERS=${WORKERS:-4}
25
+
26
+ # Clean any prior runs.json so this sweep is self-contained.
27
+ if [ -f "$JSON" ]; then
28
+ mv "$JSON" "${JSON}.$(date +%Y%m%d_%H%M%S).bak"
29
+ fi
30
+
31
+ # Single clean baseline (level=1 of any perturbation is no-op).
32
+ echo "===== baseline (no-op, level=1) ====="
33
+ $PYTHON evaluate_robustness.py \
34
+ --real_list_path "$REAL" --fake_list_path "$FAKE" \
35
+ --ckpt "$CKPT" --demographics_csv "$CSV" \
36
+ --perturbation gaussian_noise --level 1 \
37
+ --batch_size $BATCH --loader_workers $WORKERS --gpu $GPU \
38
+ --save_json "$JSON"
39
+
40
+ # Sweep level 2..5 for every perturbation.
41
+ for P in "${PERTURBATIONS[@]}"; do
42
+ for L in 2 3 4 5; do
43
+ echo "===== $P level=$L ====="
44
+ $PYTHON evaluate_robustness.py \
45
+ --real_list_path "$REAL" --fake_list_path "$FAKE" \
46
+ --ckpt "$CKPT" --demographics_csv "$CSV" \
47
+ --perturbation "$P" --level $L \
48
+ --batch_size $BATCH --loader_workers $WORKERS --gpu $GPU \
49
+ --save_json "$JSON"
50
+ done
51
+ done
52
+
53
+ echo
54
+ echo ">>> Sweep done. Results: $JSON"
split_dataset.log ADDED
The diff for this file is too large to render. See raw diff
 
split_dataset.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ 根据 FairTalking-Bench 的 CSV 文件划分数据集
5
+ 将预处理后的数据(datasets/AVLips/)按照 CSV 中的 basename 划分为 train/val/test
6
+ 匹配规则:文件名包含 basename 即可(模糊匹配)
7
+ """
8
+
9
+ import os
10
+ import shutil
11
+ import pandas as pd
12
+ from pathlib import Path
13
+ from tqdm import tqdm
14
+
15
+ # 路径配置
16
+ DATASET_DIR = "/apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets"
17
+ AVLIPS_DIR = os.path.join(DATASET_DIR, "AVLips")
18
+ CSV_DIR = "/apdcephfs_gy4/share_303628665/joywu/dataset/FairTalking-Bench"
19
+
20
+ # CSV 文件
21
+ TRAIN_CSV = os.path.join(CSV_DIR, "train.csv")
22
+ VAL_CSV = os.path.join(CSV_DIR, "val.csv")
23
+ TEST_CSV = os.path.join(CSV_DIR, "test.csv")
24
+
25
+ # 输出目录
26
+ OUTPUT_DIR = os.path.join(DATASET_DIR, "FairTalking-Bench")
27
+
28
+
29
+ def load_basenames(csv_path):
30
+ """从 CSV 文件加载 basename 列表和对应的 label"""
31
+ df = pd.read_csv(csv_path)
32
+ # 返回 basename -> label 的字典
33
+ basename_dict = {}
34
+ for _, row in df.iterrows():
35
+ basename = row['basename']
36
+ label = row['Label'] # 0=Real, 1=Fake
37
+ basename_dict[basename] = label
38
+ return basename_dict
39
+
40
+
41
+ def find_and_copy_files(avlips_dir, basename_dict, output_split_dir):
42
+ """
43
+ 在 AVLips 目录中查找匹配的文件,并复制到输出目录
44
+ 匹配规则:文件名包含 basename 即可
45
+ 优化:使用反向索引,先构建文件列表,然后直接匹配 basename
46
+ """
47
+ # 创建输出目录
48
+ real_output_dir = os.path.join(output_split_dir, "0_real")
49
+ fake_output_dir = os.path.join(output_split_dir, "1_fake")
50
+ os.makedirs(real_output_dir, exist_ok=True)
51
+ os.makedirs(fake_output_dir, exist_ok=True)
52
+
53
+ # 统计
54
+ real_count = 0
55
+ fake_count = 0
56
+ matched_files = set() # 记录已匹配的文件,避免重复
57
+
58
+ # 获取所有 basename
59
+ basenames = list(basename_dict.keys())
60
+
61
+ print(f" 开始匹配 {len(basenames)} 个 basename...")
62
+
63
+ # 遍历每个 basename,在 AVLips 目录中查找匹配的文件
64
+ for basename in tqdm(basenames, desc=" 匹配进度"):
65
+ label = basename_dict[basename] # 0=Real, 1=Fake
66
+
67
+ # 根据 label 确定要搜索的目录
68
+ if label == 0:
69
+ search_dirs = [os.path.join(avlips_dir, '0_real')]
70
+ dst_dir = real_output_dir
71
+ else:
72
+ search_dirs = [os.path.join(avlips_dir, '1_fake')]
73
+ dst_dir = fake_output_dir
74
+
75
+ # 在每个目录中查找匹配的文件
76
+ for search_dir in search_dirs:
77
+ if not os.path.exists(search_dir):
78
+ continue
79
+
80
+ # 查找包含 basename 的文件
81
+ files = os.listdir(search_dir)
82
+ for filename in files:
83
+ if basename in filename and filename.endswith('.png'):
84
+ # 找到匹配!
85
+ src_path = os.path.join(search_dir, filename)
86
+ dst_path = os.path.join(dst_dir, filename)
87
+
88
+ if not os.path.exists(dst_path):
89
+ shutil.copy2(src_path, dst_path)
90
+
91
+ # 统计
92
+ if label == 0:
93
+ real_count += 1
94
+ else:
95
+ fake_count += 1
96
+
97
+ matched_files.add(filename)
98
+
99
+ print(f" 匹配完成: {len(matched_files)} 个文件")
100
+
101
+ return real_count, fake_count
102
+
103
+
104
+ def main():
105
+ print("=" * 60)
106
+ print("开始划分 FairTalking-Bench 数据集")
107
+ print("=" * 60)
108
+
109
+ # 1. 加载 CSV 文件中的 basename
110
+ print("\n1. 加载 CSV 文件...")
111
+ train_dict = load_basenames(TRAIN_CSV)
112
+ val_dict = load_basenames(VAL_CSV)
113
+ test_dict = load_basenames(TEST_CSV)
114
+
115
+ print(f" Train: {len(train_dict)} 个样本")
116
+ print(f" Val: {len(val_dict)} 个样本")
117
+ print(f" Test: {len(test_dict)} 个样本")
118
+
119
+ # 2. 查找并复制文件
120
+ print("\n2. 查找并复制文件...")
121
+ print(f" 输出目录: {OUTPUT_DIR}")
122
+
123
+ # 训练集
124
+ print("\n 处理训练集...")
125
+ train_real, train_fake = find_and_copy_files(
126
+ AVLIPS_DIR, train_dict, os.path.join(OUTPUT_DIR, "train")
127
+ )
128
+
129
+ # 验证集
130
+ print("\n 处理验证集...")
131
+ val_real, val_fake = find_and_copy_files(
132
+ AVLIPS_DIR, val_dict, os.path.join(OUTPUT_DIR, "val")
133
+ )
134
+
135
+ # 测试集
136
+ print("\n 处理测试集...")
137
+ test_real, test_fake = find_and_copy_files(
138
+ AVLIPS_DIR, test_dict, os.path.join(OUTPUT_DIR, "test")
139
+ )
140
+
141
+ # 3. 打印统计信息
142
+ print("\n" + "=" * 60)
143
+ print("数据集划分完成!")
144
+ print("=" * 60)
145
+ print(f"\n训练集: Real={train_real}, Fake={train_fake}, Total={train_real + train_fake}")
146
+ print(f"验证集: Real={val_real}, Fake={val_fake}, Total={val_real + val_fake}")
147
+ print(f"测试集: Real={test_real}, Fake={test_fake}, Total={test_real + test_fake}")
148
+
149
+ # 4. 创建数据集信息文件
150
+ print("\n3. 创建数据集信息文件...")
151
+ create_dataset_info(OUTPUT_DIR, train_real, train_fake, val_real, val_fake, test_real, test_fake)
152
+
153
+ print("\n✅ 全部完成!")
154
+ print(f"\n数据集已保存到: {OUTPUT_DIR}")
155
+
156
+
157
+ def create_dataset_info(output_dir, train_real, train_fake, val_real, val_fake, test_real, test_fake):
158
+ """创建数据集信息文件"""
159
+ info_path = os.path.join(output_dir, "dataset_info.txt")
160
+
161
+ with open(info_path, 'w') as f:
162
+ f.write("FairTalking-Bench 数据集划分信息\n")
163
+ f.write("=" * 60 + "\n\n")
164
+
165
+ f.write("数据来源:\n")
166
+ f.write(f" CSV 目录: {CSV_DIR}\n")
167
+ f.write(f" 预处理数据: {AVLIPS_DIR}\n\n")
168
+
169
+ f.write("匹配规则:\n")
170
+ f.write(" 文件名包含 basename 即可(模糊匹配)\n\n")
171
+
172
+ f.write("数据集划分:\n")
173
+ f.write(f" 训练集: Real={train_real}, Fake={train_fake}, Total={train_real + train_fake}\n")
174
+ f.write(f" 验证集: Real={val_real}, Fake={val_fake}, Total={val_real + val_fake}\n")
175
+ f.write(f" 测试集: Real={test_real}, Fake={test_fake}, Total={test_real + test_fake}\n\n")
176
+
177
+ f.write("目录结构:\n")
178
+ f.write(f" {output_dir}/\n")
179
+ f.write(f" ├── train/\n")
180
+ f.write(f" │ ├── 0_real/ ({train_real} 张图片)\n")
181
+ f.write(f" │ └── 1_fake/ ({train_fake} 张图片)\n")
182
+ f.write(f" ├── val/\n")
183
+ f.write(f" │ ├── 0_real/ ({val_real} 张图片)\n")
184
+ f.write(f" │ └── 1_fake/ ({val_fake} 张图片)\n")
185
+ f.write(f" └── test/\n")
186
+ f.write(f" ├── 0_real/ ({test_real} 张图片)\n")
187
+ f.write(f" └── 1_fake/ ({test_fake} 张图片)\n")
188
+
189
+ print(f" 信息文件已保存: {info_path}")
190
+
191
+
192
+ if __name__ == "__main__":
193
+ main()
train.log ADDED
@@ -0,0 +1,1126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ nohup: ignoring input
2
+ ----------------- Options ---------------
3
+ arch: CLIP:ViT-L/14
4
+ batch_size: 32 [default: 10]
5
+ beta1: 0.9
6
+ blur_sig: 0
7
+ checkpoints_dir: ./checkpoints
8
+ class_bal: False
9
+ data_label: train
10
+ epoch: 50 [default: 100]
11
+ fake_list_path: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake
12
+ fine_tune: False
13
+ fix_backbone: False
14
+ fix_encoder: False
15
+ gpu_ids: 1
16
+ isTrain: True [default: None]
17
+ jpg_method: cv2
18
+ jpg_qual: 75
19
+ loss_freq: 100
20
+ lr: 2e-09
21
+ name: lipfd_train [default: experiment_name]
22
+ num_threads: 0
23
+ optim: adam
24
+ pretrained_model: ./checkpoints/experiment_name/model_epoch_29.pth
25
+ real_list_path: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/0_real
26
+ rz_interp: bilinear
27
+ save_epoch_freq: 1
28
+ serial_batches: False
29
+ suffix:
30
+ train_split: train
31
+ val_split: val
32
+ weight_decay: 0.0001
33
+ ----------------- End -------------------
34
+ Length of data loader: 1483
35
+ Length of val loader: 189
36
+ epoch: 0
37
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
38
+ warnings.warn(
39
+ Train loss: 109.3497085571289 step: 100
40
+ Train loss: 115.77810668945312 step: 200
41
+ Train loss: 87.44400787353516 step: 300
42
+ Train loss: 121.6205062866211 step: 400
43
+ Train loss: 98.32791137695312 step: 500
44
+ Train loss: 105.16156005859375 step: 600
45
+ Train loss: 126.1203384399414 step: 700
46
+ Train loss: 97.93379211425781 step: 800
47
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
48
+ Train loss: 115.77715301513672 step: 900
49
+ Train loss: 102.43711853027344 step: 1000
50
+ Train loss: 98.23110961914062 step: 1100
51
+ Train loss: 107.89041137695312 step: 1200
52
+ Train loss: 121.88636779785156 step: 1300
53
+ Train loss: 93.9386978149414 step: 1400
54
+ saving the model at the end of epoch 0
55
+ validating...
56
+ (Val @ epoch 0) acc: 0.5619205298013245 ap: 0.5358050929646152 fpr: 0.5423841059602649 fnr: 0.3337748344370861
57
+ epoch: 1
58
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
59
+ warnings.warn(
60
+ Train loss: 80.58499145507812 step: 1500
61
+ Train loss: 93.76890563964844 step: 1600
62
+ Train loss: 99.49382019042969 step: 1700
63
+ Train loss: 114.85481262207031 step: 1800
64
+ Train loss: 111.15044403076172 step: 1900
65
+ Train loss: 98.20150756835938 step: 2000
66
+ Train loss: 108.94288635253906 step: 2100
67
+ Train loss: 97.31046295166016 step: 2200
68
+ Train loss: 111.14601135253906 step: 2300
69
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
70
+ Train loss: 99.89578247070312 step: 2400
71
+ Train loss: 104.52080535888672 step: 2500
72
+ Train loss: 102.98640441894531 step: 2600
73
+ Train loss: 110.73353576660156 step: 2700
74
+ Train loss: 110.9141616821289 step: 2800
75
+ Train loss: 102.97096252441406 step: 2900
76
+ saving the model at the end of epoch 1
77
+ validating...
78
+ (Val @ epoch 1) acc: 0.5668874172185431 ap: 0.5403939443490584 fpr: 0.6112582781456953 fnr: 0.25496688741721857
79
+ epoch: 2
80
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
81
+ warnings.warn(
82
+ Train loss: 103.4789810180664 step: 3000
83
+ Train loss: 103.80142211914062 step: 3100
84
+ Train loss: 104.60528564453125 step: 3200
85
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
86
+ Train loss: 104.47315979003906 step: 3300
87
+ Train loss: 117.82144165039062 step: 3400
88
+ Train loss: 107.26661682128906 step: 3500
89
+ Train loss: 107.14081573486328 step: 3600
90
+ Train loss: 120.1827163696289 step: 3700
91
+ Train loss: 106.52513122558594 step: 3800
92
+ Train loss: 113.37628173828125 step: 3900
93
+ Train loss: 95.05484008789062 step: 4000
94
+ Train loss: 103.19268035888672 step: 4100
95
+ Train loss: 98.6756591796875 step: 4200
96
+ Train loss: 95.58908081054688 step: 4300
97
+ Train loss: 109.18098449707031 step: 4400
98
+ saving the model at the end of epoch 2
99
+ validating...
100
+ (Val @ epoch 2) acc: 0.7384105960264901 ap: 0.6719250858323706 fpr: 0.22251655629139072 fnr: 0.30066225165562915
101
+ epoch: 3
102
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
103
+ warnings.warn(
104
+ Train loss: 95.00332641601562 step: 4500
105
+ Train loss: 99.6748046875 step: 4600
106
+ Train loss: 92.31637573242188 step: 4700
107
+ Train loss: 116.52984619140625 step: 4800
108
+ Train loss: 127.14207458496094 step: 4900
109
+ Train loss: 109.15467834472656 step: 5000
110
+ Train loss: 116.30558776855469 step: 5100
111
+ Train loss: 109.86700439453125 step: 5200
112
+ Train loss: 109.25109100341797 step: 5300
113
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
114
+ Train loss: 104.51777648925781 step: 5400
115
+ Train loss: 113.69713592529297 step: 5500
116
+ Train loss: 111.95301818847656 step: 5600
117
+ Train loss: 103.20728302001953 step: 5700
118
+ Train loss: 94.30152130126953 step: 5800
119
+ Train loss: 98.17637634277344 step: 5900
120
+ saving the model at the end of epoch 3
121
+ validating...
122
+ (Val @ epoch 3) acc: 0.7683774834437086 ap: 0.7047433801685381 fpr: 0.22119205298013245 fnr: 0.24205298013245033
123
+ epoch: 4
124
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
125
+ warnings.warn(
126
+ Train loss: 105.40957641601562 step: 6000
127
+ Train loss: 90.19412231445312 step: 6100
128
+ Train loss: 119.46781158447266 step: 6200
129
+ Train loss: 111.60482788085938 step: 6300
130
+ Train loss: 91.49681854248047 step: 6400
131
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
132
+ Train loss: 105.05416870117188 step: 6500
133
+ Train loss: 93.8360595703125 step: 6600
134
+ Train loss: 113.2322998046875 step: 6700
135
+ Train loss: 94.4849853515625 step: 6800
136
+ Train loss: 104.68202209472656 step: 6900
137
+ Train loss: 109.71572875976562 step: 7000
138
+ Train loss: 101.18453216552734 step: 7100
139
+ Train loss: 110.65788269042969 step: 7200
140
+ Train loss: 94.93778991699219 step: 7300
141
+ Train loss: 98.08305358886719 step: 7400
142
+ saving the model at the end of epoch 4
143
+ validating...
144
+ (Val @ epoch 4) acc: 0.8084437086092715 ap: 0.7422743564712114 fpr: 0.15132450331125827 fnr: 0.23178807947019867
145
+ epoch: 5
146
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
147
+ warnings.warn(
148
+ Train loss: 119.11969757080078 step: 7500
149
+ Train loss: 101.54550170898438 step: 7600
150
+ Train loss: 125.54096221923828 step: 7700
151
+ Train loss: 107.59408569335938 step: 7800
152
+ Train loss: 90.32762145996094 step: 7900
153
+ Train loss: 105.04289245605469 step: 8000
154
+ Train loss: 118.83558654785156 step: 8100
155
+ Train loss: 108.56706237792969 step: 8200
156
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
157
+ Train loss: 79.27407836914062 step: 8300
158
+ Train loss: 78.02943420410156 step: 8400
159
+ Train loss: 100.42111206054688 step: 8500
160
+ Train loss: 111.81028747558594 step: 8600
161
+ Train loss: 87.120849609375 step: 8700
162
+ Train loss: 95.80047607421875 step: 8800
163
+ saving the model at the end of epoch 5
164
+ validating...
165
+ (Val @ epoch 5) acc: 0.8337748344370861 ap: 0.7723560796362805 fpr: 0.1380794701986755 fnr: 0.1943708609271523
166
+ epoch: 6
167
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
168
+ warnings.warn(
169
+ Train loss: 101.03681945800781 step: 8900
170
+ Train loss: 100.72366333007812 step: 9000
171
+ Train loss: 100.6364517211914 step: 9100
172
+ Train loss: 92.65306854248047 step: 9200
173
+ Train loss: 90.16053771972656 step: 9300
174
+ Train loss: 96.73390197753906 step: 9400
175
+ Train loss: 106.46004486083984 step: 9500
176
+ Train loss: 103.21466064453125 step: 9600
177
+ Train loss: 116.55767822265625 step: 9700
178
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
179
+ Train loss: 85.55316162109375 step: 9800
180
+ Train loss: 96.09256744384766 step: 9900
181
+ Train loss: 102.47693634033203 step: 10000
182
+ Train loss: 81.52528381347656 step: 10100
183
+ Train loss: 108.37000274658203 step: 10200
184
+ Train loss: 103.06450653076172 step: 10300
185
+ saving the model at the end of epoch 6
186
+ validating...
187
+ (Val @ epoch 6) acc: 0.8528145695364239 ap: 0.7921117857965466 fpr: 0.10927152317880795 fnr: 0.18509933774834436
188
+ epoch: 7
189
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
190
+ warnings.warn(
191
+ Train loss: 98.67803955078125 step: 10400
192
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
193
+ Train loss: 76.78703308105469 step: 10500
194
+ Train loss: 85.51482391357422 step: 10600
195
+ Train loss: 92.47024536132812 step: 10700
196
+ Train loss: 114.7383804321289 step: 10800
197
+ Train loss: 102.96634674072266 step: 10900
198
+ Train loss: 87.48692321777344 step: 11000
199
+ Train loss: 90.52207946777344 step: 11100
200
+ Train loss: 111.1252212524414 step: 11200
201
+ Train loss: 87.54425811767578 step: 11300
202
+ Train loss: 105.98014831542969 step: 11400
203
+ Train loss: 90.05438232421875 step: 11500
204
+ Train loss: 113.97802734375 step: 11600
205
+ Train loss: 102.34657287597656 step: 11700
206
+ Train loss: 84.95005798339844 step: 11800
207
+ saving the model at the end of epoch 7
208
+ validating...
209
+ (Val @ epoch 7) acc: 0.8683774834437086 ap: 0.8040541849307241 fpr: 0.06556291390728476 fnr: 0.19768211920529802
210
+ epoch: 8
211
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
212
+ warnings.warn(
213
+ Train loss: 85.20083618164062 step: 11900
214
+ Train loss: 87.54823303222656 step: 12000
215
+ Train loss: 113.52896881103516 step: 12100
216
+ Train loss: 129.43238830566406 step: 12200
217
+ Train loss: 114.55952453613281 step: 12300
218
+ Train loss: 103.117431640625 step: 12400
219
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
220
+ Train loss: 91.63424682617188 step: 12500
221
+ Train loss: 95.65892028808594 step: 12600
222
+ Train loss: 90.61808776855469 step: 12700
223
+ Train loss: 96.25401306152344 step: 12800
224
+ Train loss: 97.88920593261719 step: 12900
225
+ Train loss: 86.9149398803711 step: 13000
226
+ Train loss: 102.21635437011719 step: 13100
227
+ Train loss: 109.04608917236328 step: 13200
228
+ Train loss: 125.03392028808594 step: 13300
229
+ saving the model at the end of epoch 8
230
+ validating...
231
+ (Val @ epoch 8) acc: 0.8783112582781457 ap: 0.8186793368354413 fpr: 0.06920529801324503 fnr: 0.1741721854304636
232
+ epoch: 9
233
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
234
+ warnings.warn(
235
+ Train loss: 82.39558410644531 step: 13400
236
+ Train loss: 95.42220306396484 step: 13500
237
+ Train loss: 86.77865600585938 step: 13600
238
+ Train loss: 85.80287170410156 step: 13700
239
+ Train loss: 90.50550842285156 step: 13800
240
+ Train loss: 117.10944366455078 step: 13900
241
+ Train loss: 101.46859741210938 step: 14000
242
+ Train loss: 129.0438995361328 step: 14100
243
+ Train loss: 91.16072845458984 step: 14200
244
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
245
+ Train loss: 101.34473419189453 step: 14300
246
+ Train loss: 111.5604019165039 step: 14400
247
+ Train loss: 113.9402847290039 step: 14500
248
+ Train loss: 102.88592529296875 step: 14600
249
+ Train loss: 91.57630920410156 step: 14700
250
+ Train loss: 105.73886108398438 step: 14800
251
+ saving the model at the end of epoch 9
252
+ validating...
253
+ (Val @ epoch 9) acc: 0.8816225165562914 ap: 0.8196018733092221 fpr: 0.052980132450331126 fnr: 0.1837748344370861
254
+ epoch: 10
255
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
256
+ warnings.warn(
257
+ Train loss: 97.87602233886719 step: 14900
258
+ Train loss: 95.77507781982422 step: 15000
259
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
260
+ Train loss: 95.00900268554688 step: 15100
261
+ Train loss: 107.40650939941406 step: 15200
262
+ Train loss: 96.98809814453125 step: 15300
263
+ Train loss: 112.39302062988281 step: 15400
264
+ Train loss: 88.38487243652344 step: 15500
265
+ Train loss: 101.34196472167969 step: 15600
266
+ Train loss: 102.19132995605469 step: 15700
267
+ Train loss: 113.40335845947266 step: 15800
268
+ Train loss: 89.87989044189453 step: 15900
269
+ Train loss: 104.63227081298828 step: 16000
270
+ Train loss: 98.57897186279297 step: 16100
271
+ Train loss: 86.28732299804688 step: 16200
272
+ Train loss: 101.2440185546875 step: 16300
273
+ saving the model at the end of epoch 10
274
+ validating...
275
+ (Val @ epoch 10) acc: 0.8892384105960265 ap: 0.8295498309705669 fpr: 0.04933774834437086 fnr: 0.17218543046357615
276
+ epoch: 11
277
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
278
+ warnings.warn(
279
+ Train loss: 108.46096801757812 step: 16400
280
+ Train loss: 105.14181518554688 step: 16500
281
+ Train loss: 93.53913116455078 step: 16600
282
+ Train loss: 116.83553314208984 step: 16700
283
+ Train loss: 90.81753540039062 step: 16800
284
+ Train loss: 125.16203308105469 step: 16900
285
+ Train loss: 93.55419921875 step: 17000
286
+ Train loss: 86.73138427734375 step: 17100
287
+ Train loss: 94.1943588256836 step: 17200
288
+ Train loss: 82.45521545410156 step: 17300
289
+ Train loss: 96.87867736816406 step: 17400
290
+ Train loss: 79.26760864257812 step: 17500
291
+ Train loss: 99.71473693847656 step: 17600
292
+ Train loss: 101.4261474609375 step: 17700
293
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
294
+ saving the model at the end of epoch 11
295
+ validating...
296
+ (Val @ epoch 11) acc: 0.895364238410596 ap: 0.8384289589972633 fpr: 0.04933774834437086 fnr: 0.15993377483443708
297
+ epoch: 12
298
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
299
+ warnings.warn(
300
+ Train loss: 99.41751861572266 step: 17800
301
+ Train loss: 100.92225646972656 step: 17900
302
+ Train loss: 100.92166900634766 step: 18000
303
+ Train loss: 80.60731506347656 step: 18100
304
+ Train loss: 84.21905517578125 step: 18200
305
+ Train loss: 99.12002563476562 step: 18300
306
+ Train loss: 97.47544860839844 step: 18400
307
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
308
+ Train loss: 95.96418762207031 step: 18500
309
+ Train loss: 92.93983459472656 step: 18600
310
+ Train loss: 102.73402404785156 step: 18700
311
+ Train loss: 115.28011322021484 step: 18800
312
+ Train loss: 78.9912109375 step: 18900
313
+ Train loss: 96.33280944824219 step: 19000
314
+ Train loss: 86.17536926269531 step: 19100
315
+ Train loss: 99.39048767089844 step: 19200
316
+ saving the model at the end of epoch 12
317
+ validating...
318
+ (Val @ epoch 12) acc: 0.8948675496688742 ap: 0.8358056681580142 fpr: 0.041721854304635764 fnr: 0.16854304635761588
319
+ epoch: 13
320
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
321
+ warnings.warn(
322
+ Train loss: 97.01101684570312 step: 19300
323
+ Train loss: 99.92607116699219 step: 19400
324
+ Train loss: 94.14410400390625 step: 19500
325
+ Train loss: 108.56205749511719 step: 19600
326
+ Train loss: 100.33192443847656 step: 19700
327
+ Train loss: 119.96015167236328 step: 19800
328
+ Train loss: 100.62596130371094 step: 19900
329
+ Train loss: 89.90122985839844 step: 20000
330
+ Train loss: 104.45906066894531 step: 20100
331
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
332
+ Train loss: 109.33349609375 step: 20200
333
+ Train loss: 104.80198669433594 step: 20300
334
+ Train loss: 101.63945770263672 step: 20400
335
+ Train loss: 93.26719665527344 step: 20500
336
+ Train loss: 89.44151306152344 step: 20600
337
+ Train loss: 88.83653259277344 step: 20700
338
+ saving the model at the end of epoch 13
339
+ validating...
340
+ (Val @ epoch 13) acc: 0.9021523178807948 ap: 0.8468278718816762 fpr: 0.04304635761589404 fnr: 0.15264900662251657
341
+ epoch: 14
342
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
343
+ warnings.warn(
344
+ Train loss: 92.56515502929688 step: 20800
345
+ Train loss: 112.10537719726562 step: 20900
346
+ Train loss: 92.1612548828125 step: 21000
347
+ Train loss: 100.8740234375 step: 21100
348
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
349
+ Train loss: 89.64739227294922 step: 21200
350
+ Train loss: 105.49078369140625 step: 21300
351
+ Train loss: 81.24507904052734 step: 21400
352
+ Train loss: 93.61893463134766 step: 21500
353
+ Train loss: 105.0328369140625 step: 21600
354
+ Train loss: 81.52472686767578 step: 21700
355
+ Train loss: 82.63867950439453 step: 21800
356
+ Train loss: 93.63219451904297 step: 21900
357
+ Train loss: 88.57166290283203 step: 22000
358
+ Train loss: 95.90657806396484 step: 22100
359
+ Train loss: 103.16031646728516 step: 22200
360
+ saving the model at the end of epoch 14
361
+ validating...
362
+ (Val @ epoch 14) acc: 0.9026490066225166 ap: 0.8462686098988782 fpr: 0.0380794701986755 fnr: 0.1566225165562914
363
+ epoch: 15
364
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
365
+ warnings.warn(
366
+ Train loss: 114.83440399169922 step: 22300
367
+ Train loss: 108.83474731445312 step: 22400
368
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
369
+ Train loss: 88.62757873535156 step: 22500
370
+ Train loss: 96.61287689208984 step: 22600
371
+ Train loss: 115.21736145019531 step: 22700
372
+ Train loss: 89.04222106933594 step: 22800
373
+ Train loss: 88.95414733886719 step: 22900
374
+ Train loss: 85.84208679199219 step: 23000
375
+ Train loss: 114.43083190917969 step: 23100
376
+ Train loss: 111.42693328857422 step: 23200
377
+ Train loss: 101.97541809082031 step: 23300
378
+ Train loss: 103.68124389648438 step: 23400
379
+ Train loss: 88.98529052734375 step: 23500
380
+ Train loss: 88.13697814941406 step: 23600
381
+ Train loss: 96.48775482177734 step: 23700
382
+ saving the model at the end of epoch 15
383
+ validating...
384
+ (Val @ epoch 15) acc: 0.904635761589404 ap: 0.8482638373065826 fpr: 0.03443708609271523 fnr: 0.1562913907284768
385
+ epoch: 16
386
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
387
+ warnings.warn(
388
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
389
+ Train loss: 82.79197692871094 step: 23800
390
+ Train loss: 92.29851531982422 step: 23900
391
+ Train loss: 101.32656860351562 step: 24000
392
+ Train loss: 82.86312866210938 step: 24100
393
+ Train loss: 99.44190979003906 step: 24200
394
+ Train loss: 114.21587371826172 step: 24300
395
+ Train loss: 93.10935974121094 step: 24400
396
+ Train loss: 110.8064193725586 step: 24500
397
+ Train loss: 107.86590576171875 step: 24600
398
+ Train loss: 104.00509643554688 step: 24700
399
+ Train loss: 105.76403045654297 step: 24800
400
+ Train loss: 107.95489501953125 step: 24900
401
+ Train loss: 103.10502624511719 step: 25000
402
+ Train loss: 96.59196472167969 step: 25100
403
+ Train loss: 99.68357849121094 step: 25200
404
+ saving the model at the end of epoch 16
405
+ validating...
406
+ (Val @ epoch 16) acc: 0.9076158940397351 ap: 0.852086660247679 fpr: 0.032119205298013244 fnr: 0.15264900662251657
407
+ epoch: 17
408
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
409
+ warnings.warn(
410
+ Train loss: 92.31273651123047 step: 25300
411
+ Train loss: 84.96509552001953 step: 25400
412
+ Train loss: 86.664306640625 step: 25500
413
+ Train loss: 108.47801208496094 step: 25600
414
+ Train loss: 84.15589904785156 step: 25700
415
+ Train loss: 106.80313873291016 step: 25800
416
+ Train loss: 100.79236602783203 step: 25900
417
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
418
+ Train loss: 103.33578491210938 step: 26000
419
+ Train loss: 88.80908966064453 step: 26100
420
+ Train loss: 99.35258483886719 step: 26200
421
+ Train loss: 92.63272094726562 step: 26300
422
+ Train loss: 99.22555541992188 step: 26400
423
+ Train loss: 81.28981018066406 step: 26500
424
+ Train loss: 92.94877624511719 step: 26600
425
+ saving the model at the end of epoch 17
426
+ validating...
427
+ (Val @ epoch 17) acc: 0.9135761589403973 ap: 0.8610761985014281 fpr: 0.032119205298013244 fnr: 0.14072847682119205
428
+ epoch: 18
429
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
430
+ warnings.warn(
431
+ Train loss: 104.60865783691406 step: 26700
432
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
433
+ Train loss: 88.01316833496094 step: 26800
434
+ Train loss: 95.64061737060547 step: 26900
435
+ Train loss: 96.63502502441406 step: 27000
436
+ Train loss: 97.56912231445312 step: 27100
437
+ Train loss: 96.4901123046875 step: 27200
438
+ Train loss: 96.18511962890625 step: 27300
439
+ Train loss: 85.32862854003906 step: 27400
440
+ Train loss: 102.43637084960938 step: 27500
441
+ Train loss: 101.28318786621094 step: 27600
442
+ Train loss: 110.92155456542969 step: 27700
443
+ Train loss: 92.72991943359375 step: 27800
444
+ Train loss: 100.44973754882812 step: 27900
445
+ Train loss: 99.80447387695312 step: 28000
446
+ Train loss: 98.5571517944336 step: 28100
447
+ saving the model at the end of epoch 18
448
+ validating...
449
+ (Val @ epoch 18) acc: 0.9124172185430464 ap: 0.8580459269467713 fpr: 0.02748344370860927 fnr: 0.147682119205298
450
+ epoch: 19
451
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
452
+ warnings.warn(
453
+ Train loss: 89.30645751953125 step: 28200
454
+ Train loss: 95.78688049316406 step: 28300
455
+ Train loss: 100.19153594970703 step: 28400
456
+ Train loss: 89.90309143066406 step: 28500
457
+ Train loss: 103.15199279785156 step: 28600
458
+ Train loss: 95.88514709472656 step: 28700
459
+ Train loss: 77.65068817138672 step: 28800
460
+ Train loss: 95.78532409667969 step: 28900
461
+ Train loss: 91.47555541992188 step: 29000
462
+ Train loss: 102.67447662353516 step: 29100
463
+ Train loss: 85.68608093261719 step: 29200
464
+ Train loss: 81.28839111328125 step: 29300
465
+ Train loss: 87.3929672241211 step: 29400
466
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
467
+ Train loss: 127.06197357177734 step: 29500
468
+ Train loss: 88.83319854736328 step: 29600
469
+ saving the model at the end of epoch 19
470
+ validating...
471
+ (Val @ epoch 19) acc: 0.9149006622516557 ap: 0.8619897276184927 fpr: 0.028145695364238412 fnr: 0.14205298013245032
472
+ epoch: 20
473
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
474
+ warnings.warn(
475
+ Train loss: 103.29493713378906 step: 29700
476
+ Train loss: 95.25360107421875 step: 29800
477
+ Train loss: 95.465576171875 step: 29900
478
+ Train loss: 87.75604248046875 step: 30000
479
+ Train loss: 92.74017333984375 step: 30100
480
+ Train loss: 86.07817077636719 step: 30200
481
+ Train loss: 98.4383544921875 step: 30300
482
+ Train loss: 95.09693908691406 step: 30400
483
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
484
+ Train loss: 93.51901245117188 step: 30500
485
+ Train loss: 93.16593933105469 step: 30600
486
+ Train loss: 94.72856140136719 step: 30700
487
+ Train loss: 96.36589050292969 step: 30800
488
+ Train loss: 81.53694152832031 step: 30900
489
+ Train loss: 111.12959289550781 step: 31000
490
+ Train loss: 91.42665100097656 step: 31100
491
+ saving the model at the end of epoch 20
492
+ validating...
493
+ (Val @ epoch 20) acc: 0.9147350993377483 ap: 0.8610072160162654 fpr: 0.025496688741721854 fnr: 0.14503311258278145
494
+ epoch: 21
495
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
496
+ warnings.warn(
497
+ Train loss: 98.46931457519531 step: 31200
498
+ Train loss: 88.39454650878906 step: 31300
499
+ Train loss: 86.25625610351562 step: 31400
500
+ Train loss: 91.50813293457031 step: 31500
501
+ Train loss: 103.72244262695312 step: 31600
502
+ Train loss: 96.97940063476562 step: 31700
503
+ Train loss: 129.3763427734375 step: 31800
504
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
505
+ Train loss: 87.54872131347656 step: 31900
506
+ Train loss: 110.87643432617188 step: 32000
507
+ Train loss: 94.82489013671875 step: 32100
508
+ Train loss: 91.09426879882812 step: 32200
509
+ Train loss: 141.98573303222656 step: 32300
510
+ Train loss: 91.30592346191406 step: 32400
511
+ Train loss: 91.48355102539062 step: 32500
512
+ Train loss: 84.7899169921875 step: 32600
513
+ saving the model at the end of epoch 21
514
+ validating...
515
+ (Val @ epoch 21) acc: 0.9175496688741722 ap: 0.8655735635765534 fpr: 0.026490066225165563 fnr: 0.13841059602649006
516
+ epoch: 22
517
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
518
+ warnings.warn(
519
+ Train loss: 81.1429443359375 step: 32700
520
+ Train loss: 80.49852752685547 step: 32800
521
+ Train loss: 103.57378387451172 step: 32900
522
+ Train loss: 115.09785461425781 step: 33000
523
+ Train loss: 100.0188980102539 step: 33100
524
+ Train loss: 117.90495300292969 step: 33200
525
+ Train loss: 115.60507202148438 step: 33300
526
+ Train loss: 95.4669189453125 step: 33400
527
+ Train loss: 92.07056427001953 step: 33500
528
+ Train loss: 94.75532531738281 step: 33600
529
+ Train loss: 104.36040496826172 step: 33700
530
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
531
+ Train loss: 102.83029174804688 step: 33800
532
+ Train loss: 107.6717529296875 step: 33900
533
+ Train loss: 95.68386840820312 step: 34000
534
+ Train loss: 99.3794174194336 step: 34100
535
+ saving the model at the end of epoch 22
536
+ validating...
537
+ (Val @ epoch 22) acc: 0.9193708609271524 ap: 0.8676197734205308 fpr: 0.02384105960264901 fnr: 0.13741721854304637
538
+ epoch: 23
539
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
540
+ warnings.warn(
541
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
542
+ Train loss: 107.59786987304688 step: 34200
543
+ Train loss: 114.41547393798828 step: 34300
544
+ Train loss: 98.87919616699219 step: 34400
545
+ Train loss: 103.96318054199219 step: 34500
546
+ Train loss: 100.78030395507812 step: 34600
547
+ Train loss: 102.7208480834961 step: 34700
548
+ Train loss: 107.3170166015625 step: 34800
549
+ Train loss: 70.77960205078125 step: 34900
550
+ Train loss: 107.55149841308594 step: 35000
551
+ Train loss: 95.44448852539062 step: 35100
552
+ Train loss: 94.88804626464844 step: 35200
553
+ Train loss: 86.25000762939453 step: 35300
554
+ Train loss: 102.06913757324219 step: 35400
555
+ Train loss: 92.03421020507812 step: 35500
556
+ saving the model at the end of epoch 23
557
+ validating...
558
+ (Val @ epoch 23) acc: 0.9218543046357616 ap: 0.871453551393735 fpr: 0.02384105960264901 fnr: 0.13245033112582782
559
+ epoch: 24
560
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
561
+ warnings.warn(
562
+ Train loss: 101.97744750976562 step: 35600
563
+ Train loss: 81.46246337890625 step: 35700
564
+ Train loss: 94.9013671875 step: 35800
565
+ Train loss: 91.16714477539062 step: 35900
566
+ Train loss: 95.36466979980469 step: 36000
567
+ Train loss: 106.69194030761719 step: 36100
568
+ Train loss: 95.71537780761719 step: 36200
569
+ Train loss: 95.00849914550781 step: 36300
570
+ Train loss: 104.0283203125 step: 36400
571
+ Train loss: 98.74684143066406 step: 36500
572
+ Train loss: 102.49458312988281 step: 36600
573
+ Train loss: 77.29928588867188 step: 36700
574
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
575
+ Train loss: 98.31216430664062 step: 36800
576
+ Train loss: 99.293212890625 step: 36900
577
+ Train loss: 83.95875549316406 step: 37000
578
+ saving the model at the end of epoch 24
579
+ validating...
580
+ (Val @ epoch 24) acc: 0.919205298013245 ap: 0.8667115617611424 fpr: 0.02152317880794702 fnr: 0.1400662251655629
581
+ epoch: 25
582
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
583
+ warnings.warn(
584
+ Train loss: 106.17198181152344 step: 37100
585
+ Train loss: 95.02005004882812 step: 37200
586
+ Train loss: 95.54281616210938 step: 37300
587
+ Train loss: 85.25819396972656 step: 37400
588
+ Train loss: 95.11949157714844 step: 37500
589
+ Train loss: 99.20923614501953 step: 37600
590
+ Train loss: 107.23602294921875 step: 37700
591
+ Train loss: 87.11701965332031 step: 37800
592
+ Train loss: 94.58992004394531 step: 37900
593
+ Train loss: 121.3162841796875 step: 38000
594
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
595
+ Train loss: 91.7796401977539 step: 38100
596
+ Train loss: 107.27289581298828 step: 38200
597
+ Train loss: 94.27934265136719 step: 38300
598
+ Train loss: 95.79428100585938 step: 38400
599
+ Train loss: 103.22969055175781 step: 38500
600
+ saving the model at the end of epoch 25
601
+ validating...
602
+ (Val @ epoch 25) acc: 0.9216887417218543 ap: 0.8704344488944431 fpr: 0.02119205298013245 fnr: 0.13543046357615893
603
+ epoch: 26
604
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
605
+ warnings.warn(
606
+ Train loss: 96.3729476928711 step: 38600
607
+ Train loss: 98.09357452392578 step: 38700
608
+ Train loss: 95.33633422851562 step: 38800
609
+ Train loss: 108.59393310546875 step: 38900
610
+ Train loss: 90.77816772460938 step: 39000
611
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
612
+ Train loss: 106.17906188964844 step: 39100
613
+ Train loss: 98.71460723876953 step: 39200
614
+ Train loss: 107.44701385498047 step: 39300
615
+ Train loss: 102.05140686035156 step: 39400
616
+ Train loss: 90.86222839355469 step: 39500
617
+ Train loss: 83.28683471679688 step: 39600
618
+ Train loss: 95.26985168457031 step: 39700
619
+ Train loss: 92.15057373046875 step: 39800
620
+ Train loss: 99.08290100097656 step: 39900
621
+ Train loss: 88.71820068359375 step: 40000
622
+ saving the model at the end of epoch 26
623
+ validating...
624
+ (Val @ epoch 26) acc: 0.9230132450331126 ap: 0.8722919306182526 fpr: 0.02052980132450331 fnr: 0.13344370860927152
625
+ epoch: 27
626
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
627
+ warnings.warn(
628
+ Train loss: 95.718505859375 step: 40100
629
+ Train loss: 83.5436019897461 step: 40200
630
+ Train loss: 90.60633850097656 step: 40300
631
+ Train loss: 95.76900482177734 step: 40400
632
+ Train loss: 77.22334289550781 step: 40500
633
+ Train loss: 106.1387939453125 step: 40600
634
+ Train loss: 105.90230560302734 step: 40700
635
+ Train loss: 98.82454681396484 step: 40800
636
+ Train loss: 80.53895568847656 step: 40900
637
+ Train loss: 96.0670166015625 step: 41000
638
+ Train loss: 96.09965515136719 step: 41100
639
+ Train loss: 102.98234558105469 step: 41200
640
+ Train loss: 94.43991088867188 step: 41300
641
+ Train loss: 82.52233123779297 step: 41400
642
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
643
+ Train loss: 99.63735961914062 step: 41500
644
+ saving the model at the end of epoch 27
645
+ validating...
646
+ (Val @ epoch 27) acc: 0.9231788079470199 ap: 0.8720708628922907 fpr: 0.018874172185430464 fnr: 0.1347682119205298
647
+ epoch: 28
648
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
649
+ warnings.warn(
650
+ Train loss: 94.73419189453125 step: 41600
651
+ Train loss: 86.86043548583984 step: 41700
652
+ Train loss: 94.25665283203125 step: 41800
653
+ Train loss: 87.87420654296875 step: 41900
654
+ Train loss: 94.3466796875 step: 42000
655
+ Train loss: 87.02870178222656 step: 42100
656
+ Train loss: 94.72970581054688 step: 42200
657
+ Train loss: 73.56180572509766 step: 42300
658
+ Train loss: 107.19182586669922 step: 42400
659
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
660
+ Train loss: 86.6338882446289 step: 42500
661
+ Train loss: 90.05741882324219 step: 42600
662
+ Train loss: 96.47938537597656 step: 42700
663
+ Train loss: 87.6587142944336 step: 42800
664
+ Train loss: 99.31858825683594 step: 42900
665
+ Train loss: 88.81858825683594 step: 43000
666
+ saving the model at the end of epoch 28
667
+ validating...
668
+ (Val @ epoch 28) acc: 0.9263245033112583 ap: 0.8769619526443624 fpr: 0.018874172185430464 fnr: 0.12847682119205298
669
+ epoch: 29
670
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
671
+ warnings.warn(
672
+ Train loss: 109.44593811035156 step: 43100
673
+ Train loss: 84.59053039550781 step: 43200
674
+ Train loss: 84.24394226074219 step: 43300
675
+ Train loss: 119.02490234375 step: 43400
676
+ Train loss: 101.92208862304688 step: 43500
677
+ Train loss: 105.8259048461914 step: 43600
678
+ Train loss: 98.34077453613281 step: 43700
679
+ Train loss: 105.81497192382812 step: 43800
680
+ Train loss: 91.91256713867188 step: 43900
681
+ Train loss: 99.22040557861328 step: 44000
682
+ Train loss: 94.55714416503906 step: 44100
683
+ Train loss: 97.93988037109375 step: 44200
684
+ Train loss: 84.58506774902344 step: 44300
685
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
686
+ Train loss: 80.71188354492188 step: 44400
687
+ saving the model at the end of epoch 29
688
+ validating...
689
+ (Val @ epoch 29) acc: 0.9253311258278145 ap: 0.875024502327229 fpr: 0.017549668874172187 fnr: 0.1317880794701987
690
+ epoch: 30
691
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
692
+ warnings.warn(
693
+ Train loss: 107.75877380371094 step: 44500
694
+ Train loss: 99.62721252441406 step: 44600
695
+ Train loss: 98.58932495117188 step: 44700
696
+ Train loss: 80.76273345947266 step: 44800
697
+ Train loss: 95.53893280029297 step: 44900
698
+ Train loss: 94.35447692871094 step: 45000
699
+ Train loss: 98.68751525878906 step: 45100
700
+ Train loss: 91.52035522460938 step: 45200
701
+ Train loss: 85.08636474609375 step: 45300
702
+ Train loss: 99.96929931640625 step: 45400
703
+ Train loss: 110.87091064453125 step: 45500
704
+ Train loss: 102.12557983398438 step: 45600
705
+ Train loss: 80.78931427001953 step: 45700
706
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
707
+ Train loss: 99.07274627685547 step: 45800
708
+ Train loss: 88.63421630859375 step: 45900
709
+ saving the model at the end of epoch 30
710
+ validating...
711
+ (Val @ epoch 30) acc: 0.9245033112582781 ap: 0.873643483930774 fpr: 0.017218543046357615 fnr: 0.1337748344370861
712
+ epoch: 31
713
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
714
+ warnings.warn(
715
+ Train loss: 95.41173553466797 step: 46000
716
+ Train loss: 91.78175354003906 step: 46100
717
+ Train loss: 99.63282775878906 step: 46200
718
+ Train loss: 126.46421813964844 step: 46300
719
+ Train loss: 91.29084777832031 step: 46400
720
+ Train loss: 94.41521453857422 step: 46500
721
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
722
+ Train loss: 87.62366485595703 step: 46600
723
+ Train loss: 83.82557678222656 step: 46700
724
+ Train loss: 119.25001525878906 step: 46800
725
+ Train loss: 80.16643524169922 step: 46900
726
+ Train loss: 96.1780014038086 step: 47000
727
+ Train loss: 94.11321258544922 step: 47100
728
+ Train loss: 69.96588134765625 step: 47200
729
+ Train loss: 97.95004272460938 step: 47300
730
+ Train loss: 91.87395477294922 step: 47400
731
+ saving the model at the end of epoch 31
732
+ validating...
733
+ (Val @ epoch 31) acc: 0.9253311258278145 ap: 0.8743518106575674 fpr: 0.015231788079470199 fnr: 0.13410596026490065
734
+ epoch: 32
735
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
736
+ warnings.warn(
737
+ Train loss: 94.93876647949219 step: 47500
738
+ Train loss: 74.20389556884766 step: 47600
739
+ Train loss: 93.996337890625 step: 47700
740
+ Train loss: 91.61723327636719 step: 47800
741
+ Train loss: 80.5855484008789 step: 47900
742
+ Train loss: 105.62805938720703 step: 48000
743
+ Train loss: 77.38821411132812 step: 48100
744
+ Train loss: 90.43487548828125 step: 48200
745
+ Train loss: 104.10159301757812 step: 48300
746
+ Train loss: 96.5937271118164 step: 48400
747
+ Train loss: 115.57551574707031 step: 48500
748
+ Train loss: 83.31884002685547 step: 48600
749
+ Train loss: 94.00515747070312 step: 48700
750
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
751
+ Train loss: 91.11808013916016 step: 48800
752
+ Train loss: 95.9767074584961 step: 48900
753
+ saving the model at the end of epoch 32
754
+ validating...
755
+ (Val @ epoch 32) acc: 0.9326158940397351 ap: 0.8868095052590573 fpr: 0.018543046357615896 fnr: 0.1162251655629139
756
+ epoch: 33
757
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
758
+ warnings.warn(
759
+ Train loss: 77.57847595214844 step: 49000
760
+ Train loss: 114.95893859863281 step: 49100
761
+ Train loss: 89.53807830810547 step: 49200
762
+ Train loss: 102.10774993896484 step: 49300
763
+ Train loss: 91.46820068359375 step: 49400
764
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
765
+ Train loss: 107.26177978515625 step: 49500
766
+ Train loss: 79.87150573730469 step: 49600
767
+ Train loss: 80.25978088378906 step: 49700
768
+ Train loss: 86.90876007080078 step: 49800
769
+ Train loss: 108.16836547851562 step: 49900
770
+ Train loss: 84.42555236816406 step: 50000
771
+ Train loss: 98.3057632446289 step: 50100
772
+ Train loss: 94.54742431640625 step: 50200
773
+ Train loss: 105.42430114746094 step: 50300
774
+ Train loss: 76.19158935546875 step: 50400
775
+ saving the model at the end of epoch 33
776
+ validating...
777
+ (Val @ epoch 33) acc: 0.9317880794701987 ap: 0.8850802343352012 fpr: 0.017218543046357615 fnr: 0.11920529801324503
778
+ epoch: 34
779
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
780
+ warnings.warn(
781
+ Train loss: 125.81848907470703 step: 50500
782
+ Train loss: 92.07084655761719 step: 50600
783
+ Train loss: 73.8358383178711 step: 50700
784
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
785
+ Train loss: 125.55552673339844 step: 50800
786
+ Train loss: 83.88774108886719 step: 50900
787
+ Train loss: 90.35460662841797 step: 51000
788
+ Train loss: 93.7743148803711 step: 51100
789
+ Train loss: 102.3692626953125 step: 51200
790
+ Train loss: 87.55474090576172 step: 51300
791
+ Train loss: 105.97702026367188 step: 51400
792
+ Train loss: 76.19060516357422 step: 51500
793
+ Train loss: 94.39215087890625 step: 51600
794
+ Train loss: 108.25830078125 step: 51700
795
+ Train loss: 86.64149475097656 step: 51800
796
+ Train loss: 94.81710815429688 step: 51900
797
+ saving the model at the end of epoch 34
798
+ validating...
799
+ (Val @ epoch 34) acc: 0.9312913907284768 ap: 0.8838867964195967 fpr: 0.015894039735099338 fnr: 0.12152317880794702
800
+ epoch: 35
801
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
802
+ warnings.warn(
803
+ Train loss: 76.47958374023438 step: 52000
804
+ Train loss: 102.25346374511719 step: 52100
805
+ Train loss: 100.02899169921875 step: 52200
806
+ Train loss: 76.23573303222656 step: 52300
807
+ Train loss: 90.76263427734375 step: 52400
808
+ Train loss: 96.04088592529297 step: 52500
809
+ Train loss: 95.24079895019531 step: 52600
810
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
811
+ Train loss: 97.91497802734375 step: 52700
812
+ Train loss: 97.41355895996094 step: 52800
813
+ Train loss: 97.85961151123047 step: 52900
814
+ Train loss: 114.14883422851562 step: 53000
815
+ Train loss: 94.67399597167969 step: 53100
816
+ Train loss: 102.08966064453125 step: 53200
817
+ Train loss: 91.06591796875 step: 53300
818
+ saving the model at the end of epoch 35
819
+ validating...
820
+ (Val @ epoch 35) acc: 0.9319536423841059 ap: 0.8851402935697372 fpr: 0.016556291390728478 fnr: 0.1195364238410596
821
+ epoch: 36
822
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
823
+ warnings.warn(
824
+ Train loss: 105.64775848388672 step: 53400
825
+ Train loss: 109.65997314453125 step: 53500
826
+ Train loss: 105.07560729980469 step: 53600
827
+ Train loss: 107.36741638183594 step: 53700
828
+ Train loss: 83.0212631225586 step: 53800
829
+ Train loss: 90.62057495117188 step: 53900
830
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
831
+ Train loss: 106.80844116210938 step: 54000
832
+ Train loss: 94.00015258789062 step: 54100
833
+ Train loss: 97.37210083007812 step: 54200
834
+ Train loss: 100.07282257080078 step: 54300
835
+ Train loss: 86.8153076171875 step: 54400
836
+ Train loss: 98.42520141601562 step: 54500
837
+ Train loss: 84.40351867675781 step: 54600
838
+ Train loss: 94.61422729492188 step: 54700
839
+ Train loss: 94.72000122070312 step: 54800
840
+ saving the model at the end of epoch 36
841
+ validating...
842
+ (Val @ epoch 36) acc: 0.9354304635761589 ap: 0.890912769477931 fpr: 0.017218543046357615 fnr: 0.1119205298013245
843
+ epoch: 37
844
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
845
+ warnings.warn(
846
+ Train loss: 91.30091857910156 step: 54900
847
+ Train loss: 91.02377319335938 step: 55000
848
+ Train loss: 105.36109924316406 step: 55100
849
+ Train loss: 100.18766784667969 step: 55200
850
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
851
+ Train loss: 87.48077392578125 step: 55300
852
+ Train loss: 90.96659851074219 step: 55400
853
+ Train loss: 102.36908721923828 step: 55500
854
+ Train loss: 93.92560577392578 step: 55600
855
+ Train loss: 98.06395721435547 step: 55700
856
+ Train loss: 87.72573852539062 step: 55800
857
+ Train loss: 106.69154357910156 step: 55900
858
+ Train loss: 104.80895233154297 step: 56000
859
+ Train loss: 113.35851287841797 step: 56100
860
+ Train loss: 94.14604187011719 step: 56200
861
+ Train loss: 86.715576171875 step: 56300
862
+ saving the model at the end of epoch 37
863
+ validating...
864
+ (Val @ epoch 37) acc: 0.9336092715231789 ap: 0.8871650741233064 fpr: 0.01456953642384106 fnr: 0.11821192052980133
865
+ epoch: 38
866
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
867
+ warnings.warn(
868
+ Train loss: 94.313232421875 step: 56400
869
+ Train loss: 94.04849243164062 step: 56500
870
+ Train loss: 109.79649353027344 step: 56600
871
+ Train loss: 98.18072509765625 step: 56700
872
+ Train loss: 89.97587585449219 step: 56800
873
+ Train loss: 109.39126586914062 step: 56900
874
+ Train loss: 83.82635498046875 step: 57000
875
+ Train loss: 109.32949829101562 step: 57100
876
+ Train loss: 97.58815002441406 step: 57200
877
+ Train loss: 99.30084228515625 step: 57300
878
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
879
+ Train loss: 82.94303894042969 step: 57400
880
+ Train loss: 99.66937255859375 step: 57500
881
+ Train loss: 82.54581451416016 step: 57600
882
+ Train loss: 90.79081726074219 step: 57700
883
+ Train loss: 93.85063171386719 step: 57800
884
+ saving the model at the end of epoch 38
885
+ validating...
886
+ (Val @ epoch 38) acc: 0.93658940397351 ap: 0.8921524878940557 fpr: 0.015231788079470199 fnr: 0.11158940397350993
887
+ epoch: 39
888
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
889
+ warnings.warn(
890
+ Train loss: 101.46546936035156 step: 57900
891
+ Train loss: 86.85536193847656 step: 58000
892
+ Train loss: 86.88607788085938 step: 58100
893
+ Train loss: 94.00170135498047 step: 58200
894
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
895
+ Train loss: 101.704833984375 step: 58300
896
+ Train loss: 86.93431854248047 step: 58400
897
+ Train loss: 106.63441467285156 step: 58500
898
+ Train loss: 105.39498138427734 step: 58600
899
+ Train loss: 102.37200927734375 step: 58700
900
+ Train loss: 98.33232879638672 step: 58800
901
+ Train loss: 94.26693725585938 step: 58900
902
+ Train loss: 106.35066223144531 step: 59000
903
+ Train loss: 98.30419921875 step: 59100
904
+ Train loss: 79.83206176757812 step: 59200
905
+ Train loss: 90.36638641357422 step: 59300
906
+ saving the model at the end of epoch 39
907
+ validating...
908
+ (Val @ epoch 39) acc: 0.9347682119205298 ap: 0.8886050604448648 fpr: 0.013245033112582781 fnr: 0.11721854304635762
909
+ epoch: 40
910
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
911
+ warnings.warn(
912
+ Train loss: 83.80421447753906 step: 59400
913
+ Train loss: 97.71980285644531 step: 59500
914
+ Train loss: 86.69020080566406 step: 59600
915
+ Train loss: 114.35474395751953 step: 59700
916
+ Train loss: 97.22096252441406 step: 59800
917
+ Train loss: 88.50094604492188 step: 59900
918
+ Train loss: 97.62434387207031 step: 60000
919
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
920
+ Train loss: 97.61849212646484 step: 60100
921
+ Train loss: 118.01669311523438 step: 60200
922
+ Train loss: 83.99238586425781 step: 60300
923
+ Train loss: 86.89488983154297 step: 60400
924
+ Train loss: 98.79199981689453 step: 60500
925
+ Train loss: 78.77233123779297 step: 60600
926
+ Train loss: 83.23431396484375 step: 60700
927
+ Train loss: 86.27637481689453 step: 60800
928
+ saving the model at the end of epoch 40
929
+ validating...
930
+ (Val @ epoch 40) acc: 0.9346026490066225 ap: 0.8877273707600164 fpr: 0.011258278145695364 fnr: 0.1195364238410596
931
+ epoch: 41
932
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
933
+ warnings.warn(
934
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
935
+ Train loss: 91.28060913085938 step: 60900
936
+ Train loss: 105.48225402832031 step: 61000
937
+ Train loss: 97.78602600097656 step: 61100
938
+ Train loss: 105.30380249023438 step: 61200
939
+ Train loss: 105.22386169433594 step: 61300
940
+ Train loss: 94.03921508789062 step: 61400
941
+ Train loss: 75.66316223144531 step: 61500
942
+ Train loss: 83.37248992919922 step: 61600
943
+ Train loss: 82.9482192993164 step: 61700
944
+ Train loss: 105.40867614746094 step: 61800
945
+ Train loss: 117.3250732421875 step: 61900
946
+ Train loss: 87.09813690185547 step: 62000
947
+ Train loss: 116.06901550292969 step: 62100
948
+ Train loss: 94.27781677246094 step: 62200
949
+ saving the model at the end of epoch 41
950
+ validating...
951
+ (Val @ epoch 41) acc: 0.9352649006622517 ap: 0.8892963302952812 fpr: 0.012913907284768211 fnr: 0.11655629139072848
952
+ epoch: 42
953
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
954
+ warnings.warn(
955
+ Train loss: 109.22545623779297 step: 62300
956
+ Train loss: 90.06454467773438 step: 62400
957
+ Train loss: 97.81288146972656 step: 62500
958
+ Train loss: 94.01913452148438 step: 62600
959
+ Train loss: 89.94760131835938 step: 62700
960
+ Train loss: 113.94859313964844 step: 62800
961
+ Train loss: 109.82142639160156 step: 62900
962
+ Train loss: 94.44390869140625 step: 63000
963
+ Train loss: 121.51100158691406 step: 63100
964
+ Train loss: 90.37667846679688 step: 63200
965
+ Train loss: 90.16975402832031 step: 63300
966
+ Train loss: 101.73966979980469 step: 63400
967
+ Train loss: 77.35667419433594 step: 63500
968
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
969
+ Train loss: 90.05270385742188 step: 63600
970
+ Train loss: 102.1438980102539 step: 63700
971
+ saving the model at the end of epoch 42
972
+ validating...
973
+ (Val @ epoch 42) acc: 0.9407284768211921 ap: 0.8985567058009383 fpr: 0.01423841059602649 fnr: 0.10430463576158941
974
+ epoch: 43
975
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
976
+ warnings.warn(
977
+ Train loss: 94.28565979003906 step: 63800
978
+ Train loss: 88.5025405883789 step: 63900
979
+ Train loss: 84.7755126953125 step: 64000
980
+ Train loss: 95.95376586914062 step: 64100
981
+ Train loss: 83.29885864257812 step: 64200
982
+ Train loss: 94.64238739013672 step: 64300
983
+ Train loss: 97.70860290527344 step: 64400
984
+ Train loss: 96.45343780517578 step: 64500
985
+ Train loss: 94.48623657226562 step: 64600
986
+ Train loss: 117.8350830078125 step: 64700
987
+ Train loss: 96.92566680908203 step: 64800
988
+ Train loss: 77.26060485839844 step: 64900
989
+ Train loss: 102.19673156738281 step: 65000
990
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
991
+ Train loss: 94.15009307861328 step: 65100
992
+ Train loss: 97.46650695800781 step: 65200
993
+ saving the model at the end of epoch 43
994
+ validating...
995
+ (Val @ epoch 43) acc: 0.9400662251655629 ap: 0.8972597832630945 fpr: 0.013576158940397352 fnr: 0.10629139072847682
996
+ epoch: 44
997
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
998
+ warnings.warn(
999
+ Train loss: 105.65857696533203 step: 65300
1000
+ Train loss: 85.96650695800781 step: 65400
1001
+ Train loss: 95.0820541381836 step: 65500
1002
+ Train loss: 94.70610809326172 step: 65600
1003
+ Train loss: 93.39395141601562 step: 65700
1004
+ Train loss: 100.08433532714844 step: 65800
1005
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
1006
+ Train loss: 101.28034973144531 step: 65900
1007
+ Train loss: 89.05029296875 step: 66000
1008
+ Train loss: 90.05953216552734 step: 66100
1009
+ Train loss: 87.03773498535156 step: 66200
1010
+ Train loss: 109.26770782470703 step: 66300
1011
+ Train loss: 82.67086791992188 step: 66400
1012
+ Train loss: 76.64437103271484 step: 66500
1013
+ Train loss: 86.54629516601562 step: 66600
1014
+ Train loss: 76.48202514648438 step: 66700
1015
+ saving the model at the end of epoch 44
1016
+ validating...
1017
+ (Val @ epoch 44) acc: 0.938907284768212 ap: 0.8951623726650679 fpr: 0.012913907284768211 fnr: 0.10927152317880795
1018
+ epoch: 45
1019
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
1020
+ warnings.warn(
1021
+ Train loss: 102.70532989501953 step: 66800
1022
+ Train loss: 98.54911804199219 step: 66900
1023
+ Train loss: 80.60196685791016 step: 67000
1024
+ Train loss: 89.60649108886719 step: 67100
1025
+ Train loss: 101.90727233886719 step: 67200
1026
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
1027
+ Train loss: 110.23324584960938 step: 67300
1028
+ Train loss: 90.51313781738281 step: 67400
1029
+ Train loss: 82.82902526855469 step: 67500
1030
+ Train loss: 114.34927368164062 step: 67600
1031
+ Train loss: 104.7222671508789 step: 67700
1032
+ Train loss: 104.95767211914062 step: 67800
1033
+ Train loss: 93.2955322265625 step: 67900
1034
+ Train loss: 103.30267333984375 step: 68000
1035
+ Train loss: 101.23458862304688 step: 68100
1036
+ Train loss: 90.28176879882812 step: 68200
1037
+ saving the model at the end of epoch 45
1038
+ validating...
1039
+ (Val @ epoch 45) acc: 0.9380794701986755 ap: 0.8932968424573797 fpr: 0.011258278145695364 fnr: 0.11258278145695365
1040
+ epoch: 46
1041
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
1042
+ warnings.warn(
1043
+ Train loss: 97.50723266601562 step: 68300
1044
+ Train loss: 97.13092803955078 step: 68400
1045
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
1046
+ Train loss: 89.87747192382812 step: 68500
1047
+ Train loss: 90.36524963378906 step: 68600
1048
+ Train loss: 101.256591796875 step: 68700
1049
+ Train loss: 99.16970825195312 step: 68800
1050
+ Train loss: 109.6037826538086 step: 68900
1051
+ Train loss: 105.37516784667969 step: 69000
1052
+ Train loss: 94.57360076904297 step: 69100
1053
+ Train loss: 97.98590850830078 step: 69200
1054
+ Train loss: 97.60783386230469 step: 69300
1055
+ Train loss: 85.90118408203125 step: 69400
1056
+ Train loss: 97.27726745605469 step: 69500
1057
+ Train loss: 116.9710922241211 step: 69600
1058
+ Train loss: 97.3941650390625 step: 69700
1059
+ saving the model at the end of epoch 46
1060
+ validating...
1061
+ (Val @ epoch 46) acc: 0.9397350993377483 ap: 0.895867613538835 fpr: 0.010927152317880795 fnr: 0.10960264900662252
1062
+ epoch: 47
1063
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
1064
+ warnings.warn(
1065
+ Train loss: 97.43257141113281 step: 69800
1066
+ Train loss: 94.33767700195312 step: 69900
1067
+ Train loss: 101.50326538085938 step: 70000
1068
+ Train loss: 76.67514038085938 step: 70100
1069
+ Train loss: 90.25025939941406 step: 70200
1070
+ Train loss: 82.4213638305664 step: 70300
1071
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
1072
+ Train loss: 105.03654479980469 step: 70400
1073
+ Train loss: 92.296630859375 step: 70500
1074
+ Train loss: 91.99394989013672 step: 70600
1075
+ Train loss: 76.64805603027344 step: 70700
1076
+ Train loss: 95.92701721191406 step: 70800
1077
+ Train loss: 90.02147674560547 step: 70900
1078
+ Train loss: 90.73638153076172 step: 71000
1079
+ Train loss: 89.86149597167969 step: 71100
1080
+ saving the model at the end of epoch 47
1081
+ validating...
1082
+ (Val @ epoch 47) acc: 0.9405629139072847 ap: 0.897211416794766 fpr: 0.010927152317880795 fnr: 0.10794701986754966
1083
+ epoch: 48
1084
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
1085
+ warnings.warn(
1086
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
1087
+ Train loss: 97.4541015625 step: 71200
1088
+ Train loss: 102.45660400390625 step: 71300
1089
+ Train loss: 69.94125366210938 step: 71400
1090
+ Train loss: 109.10926818847656 step: 71500
1091
+ Train loss: 97.28998565673828 step: 71600
1092
+ Train loss: 100.94027709960938 step: 71700
1093
+ Train loss: 94.3294677734375 step: 71800
1094
+ Train loss: 79.23173522949219 step: 71900
1095
+ Train loss: 107.92404174804688 step: 72000
1096
+ Train loss: 96.29600524902344 step: 72100
1097
+ Train loss: 93.08766174316406 step: 72200
1098
+ Train loss: 98.92930603027344 step: 72300
1099
+ Train loss: 102.63845825195312 step: 72400
1100
+ Train loss: 93.48680114746094 step: 72500
1101
+ Train loss: 105.561767578125 step: 72600
1102
+ saving the model at the end of epoch 48
1103
+ validating...
1104
+ (Val @ epoch 48) acc: 0.9395695364238411 ap: 0.8954934582458408 fpr: 0.010596026490066225 fnr: 0.11026490066225166
1105
+ epoch: 49
1106
+ /opt/conda/envs/LipFD/lib/python3.10/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).
1107
+ warnings.warn(
1108
+ Train loss: 89.19844818115234 step: 72700
1109
+ Train loss: 105.79002380371094 step: 72800
1110
+ Train loss: 94.37416076660156 step: 72900
1111
+ Train loss: 97.48074340820312 step: 73000
1112
+ Train loss: 76.3938980102539 step: 73100
1113
+ Train loss: 93.292236328125 step: 73200
1114
+ Train loss: 93.73245239257812 step: 73300
1115
+ Train loss: 111.39205932617188 step: 73400
1116
+ Train loss: 79.65298461914062 step: 73500
1117
+ Train loss: 83.60038757324219 step: 73600
1118
+ Train loss: 90.1827392578125 step: 73700
1119
+ Train loss: 86.8857421875 step: 73800
1120
+ WARNING: Failed to read image, skipping: /apdcephfs_gy4/share_303628665/joywu/research/LipFD/datasets/FairTalking-Bench/train/1_fake/Sonic_1135_Fake_Sonic_7.png
1121
+ Train loss: 89.89358520507812 step: 73900
1122
+ Train loss: 97.02238464355469 step: 74000
1123
+ Train loss: 101.51692962646484 step: 74100
1124
+ saving the model at the end of epoch 49
1125
+ validating...
1126
+ (Val @ epoch 49) acc: 0.9405629139072847 ap: 0.896998055371985 fpr: 0.010264900662251655 fnr: 0.10860927152317881
train.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from validate import validate
2
+ from data import create_dataloader
3
+ from trainer.trainer import Trainer
4
+ from options.train_options import TrainOptions
5
+
6
+
7
+ def get_val_opt():
8
+ val_opt = TrainOptions().parse(print_options=False)
9
+ val_opt.isTrain = False
10
+ val_opt.data_label = "val"
11
+ val_opt.real_list_path = "./datasets/FairTalking-Bench/val/0_real"
12
+ val_opt.fake_list_path = "./datasets/FairTalking-Bench/val/1_fake"
13
+ return val_opt
14
+
15
+
16
+ if __name__ == "__main__":
17
+ opt = TrainOptions().parse()
18
+ val_opt = get_val_opt()
19
+ model = Trainer(opt)
20
+
21
+ data_loader = create_dataloader(opt)
22
+ val_loader = create_dataloader(val_opt)
23
+
24
+ print("Length of data loader: %d" % (len(data_loader)))
25
+ print("Length of val loader: %d" % (len(val_loader)))
26
+
27
+ for epoch in range(opt.epoch):
28
+ model.train()
29
+ print("epoch: ", epoch + model.step_bias)
30
+ for i, (img, crops, label) in enumerate(data_loader):
31
+ model.total_steps += 1
32
+
33
+ model.set_input((img, crops, label))
34
+ model.forward()
35
+ loss = model.get_loss()
36
+
37
+ model.optimize_parameters()
38
+
39
+ if model.total_steps % opt.loss_freq == 0:
40
+ print(
41
+ "Train loss: {}\tstep: {}".format(
42
+ model.get_loss(), model.total_steps
43
+ )
44
+ )
45
+
46
+ if epoch % opt.save_epoch_freq == 0:
47
+ print("saving the model at the end of epoch %d" % (epoch + model.step_bias))
48
+ model.save_networks("model_epoch_%s.pth" % (epoch + model.step_bias))
49
+
50
+ model.eval()
51
+ ap, fpr, fnr, acc = validate(model.model, val_loader, opt.gpu_ids)
52
+ print(
53
+ "(Val @ epoch {}) acc: {} ap: {} fpr: {} fnr: {}".format(
54
+ epoch + model.step_bias, acc, ap, fpr, fnr
55
+ )
56
+ )
trainer/trainer.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import torch.nn as nn
4
+ from models import build_model, get_loss
5
+
6
+
7
+ class Trainer(nn.Module):
8
+ def __init__(self, opt):
9
+ super().__init__() # 必须先调用父类的 __init__
10
+ self.opt = opt
11
+ self.total_steps = 0
12
+ self.save_dir = os.path.join(opt.checkpoints_dir, opt.name)
13
+ self.device = (
14
+ torch.device("cuda:{}".format(opt.gpu_ids[0]))
15
+ if opt.gpu_ids
16
+ else torch.device("cpu")
17
+ )
18
+ self.opt = opt
19
+ self.model = build_model(opt.arch)
20
+
21
+ self.step_bias = (
22
+ 0
23
+ if not opt.fine_tune
24
+ else int(opt.pretrained_model.split("_")[-1].split(".")[0]) + 1
25
+ )
26
+ if opt.fine_tune:
27
+ state_dict = torch.load(opt.pretrained_model, map_location="cpu")
28
+ self.model.load_state_dict(state_dict["model"])
29
+ self.total_steps = state_dict["total_steps"]
30
+ print(f"Model loaded @ {opt.pretrained_model.split('/')[-1]}")
31
+
32
+ if opt.fix_encoder:
33
+ params = []
34
+ for name, p in self.model.named_parameters():
35
+ if name.split(".")[0] in ["encoder"]:
36
+ p.requires_grad = False
37
+ else:
38
+ p.requires_grad = False
39
+ params = self.model.parameters()
40
+
41
+ if opt.optim == "adam":
42
+ self.optimizer = torch.optim.AdamW(
43
+ params,
44
+ lr=opt.lr,
45
+ betas=(opt.beta1, 0.999),
46
+ weight_decay=opt.weight_decay,
47
+ )
48
+ elif opt.optim == "sgd":
49
+ self.optimizer = torch.optim.SGD(
50
+ params, lr=opt.lr, momentum=0.0, weight_decay=opt.weight_decay
51
+ )
52
+ else:
53
+ raise ValueError("optim should be [adam, sgd]")
54
+
55
+ self.criterion = get_loss().to(self.device)
56
+ self.criterion1 = nn.CrossEntropyLoss()
57
+
58
+ self.model.to(opt.gpu_ids[0] if torch.cuda.is_available() else "cpu")
59
+
60
+ def adjust_learning_rate(self, min_lr=1e-8):
61
+ for param_group in self.optimizer.param_groups:
62
+ if param_group["lr"] < min_lr:
63
+ return False
64
+ param_group["lr"] /= 10.0
65
+ return True
66
+
67
+ def set_input(self, input):
68
+ self.input = input[0].to(self.device)
69
+ self.crops = [[t.to(self.device) for t in sublist] for sublist in input[1]]
70
+ self.label = input[2].to(self.device).float()
71
+
72
+ def forward(self):
73
+ self.get_features()
74
+ self.output, self.weights_max, self.weights_org = self.model.forward(
75
+ self.crops, self.features
76
+ )
77
+ self.output = self.output.view(-1)
78
+ self.loss = self.criterion(
79
+ self.weights_max, self.weights_org
80
+ ) + self.criterion1(self.output, self.label)
81
+
82
+ def get_loss(self):
83
+ loss = self.loss.data.tolist()
84
+ return loss[0] if isinstance(loss, type(list())) else loss
85
+
86
+ def optimize_parameters(self):
87
+ self.optimizer.zero_grad()
88
+ self.loss.backward()
89
+ self.optimizer.step()
90
+
91
+ def get_features(self):
92
+ self.features = self.model.get_features(self.input).to(
93
+ self.device
94
+ ) # shape: (batch_size
95
+
96
+ def eval(self):
97
+ self.model.eval()
98
+
99
+ def test(self):
100
+ with torch.no_grad():
101
+ self.forward()
102
+
103
+ def save_networks(self, save_filename):
104
+ save_path = os.path.join(self.save_dir, save_filename)
105
+
106
+ # serialize model and optimizer to dict
107
+ state_dict = {
108
+ "model": self.model.state_dict(),
109
+ "optimizer": self.optimizer.state_dict(),
110
+ "total_steps": self.total_steps,
111
+ }
112
+
113
+ torch.save(state_dict, save_path)
utils.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ def get_list(path) -> list:
4
+ r"""Recursively read all files in root path"""
5
+ image_list = list()
6
+ for root, dirs, files in os.walk(path):
7
+ for f in files:
8
+ if f.split('.')[1] in ['png', 'jpg', 'jpeg']:
9
+ image_list.append(os.path.join(root, f))
10
+ return image_list
validate.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import torch
3
+ import numpy as np
4
+ import pandas as pd
5
+ from data import AVLip
6
+ import torch.utils.data
7
+ from models import build_model
8
+ from sklearn.metrics import average_precision_score, confusion_matrix, accuracy_score, roc_auc_score, roc_curve
9
+ import os
10
+
11
+
12
+ def custom_collate(batch):
13
+ """自定义 collate 函数,处理包含文件路径的批次数据"""
14
+ # batch 是一个列表,每个元素是 (img, crops, label, img_path)
15
+ imgs = torch.stack([item[0] for item in batch])
16
+
17
+ # 处理 crops(列表的列表):crops[scale_idx][sample_idx] 是一个 tensor
18
+ # 需要将其转换为:crops[scale_idx] 是一个 tensor,形状为 (batch_size, 3, 224, 224)
19
+ num_scales = len(batch[0][1]) # 尺度数(通常是3个:1.0x, 0.65x, 0.45x)
20
+ num_crops_per_scale = len(batch[0][1][0]) # 每个尺度的 crop 数量(通常是5)
21
+
22
+ crops = []
23
+ for scale_idx in range(num_scales):
24
+ scale_crops = []
25
+ for crop_idx in range(num_crops_per_scale):
26
+ # 收集 batch 中所有样本在这个尺度和 crop 索引下的 tensor
27
+ crop_tensors = [batch[sample_idx][1][scale_idx][crop_idx] for sample_idx in range(len(batch))]
28
+ # 堆叠成一个 batch tensor
29
+ crop_batch = torch.stack(crop_tensors)
30
+ scale_crops.append(crop_batch)
31
+ crops.append(scale_crops)
32
+
33
+ labels = torch.tensor([item[2] for item in batch])
34
+ img_paths = [item[3] for item in batch]
35
+
36
+ return imgs, crops, labels, img_paths
37
+
38
+
39
+ def compute_eer(y_true, y_pred_proba):
40
+ """计算 EER (Equal Error Rate) 和对应的阈值"""
41
+ # 获取 ROC 曲线上的点
42
+ fpr, tpr, thresholds = roc_curve(y_true, y_pred_proba)
43
+ fnr = 1 - tpr
44
+
45
+ # 找到 FPR 和 FNR 差异最小的点,即为 EER
46
+ eer_threshold = thresholds[np.nanargmin(np.abs(fpr - fnr))]
47
+ eer = fpr[np.nanargmin(np.abs(fpr - fnr))]
48
+
49
+ return eer, eer_threshold
50
+
51
+
52
+ def compute_acc_at_eer(y_true, y_pred_proba, eer_threshold):
53
+ """计算在 EER 阈值下的准确率"""
54
+ y_pred_binary = (y_pred_proba >= eer_threshold).astype(int)
55
+ acc = accuracy_score(y_true, y_pred_binary)
56
+ return acc
57
+
58
+
59
+ def validate(model, loader, gpu_id):
60
+ print("validating...")
61
+ device = torch.device(f"cuda:{gpu_id[0]}" if torch.cuda.is_available() else "cpu")
62
+ with torch.no_grad():
63
+ y_true, y_pred = [], []
64
+ img_paths = [] # 存储每个样本的文件路径
65
+ for batch_data in loader:
66
+ # 解包数据:现在使用 custom_collate,返回 (imgs, crops, labels, img_paths)
67
+ imgs, crops, labels, batch_paths = batch_data
68
+
69
+ # 保存文件路径
70
+ img_paths.extend(batch_paths)
71
+
72
+ img_tens = imgs.to(device)
73
+ # crops 现在是正确格式:crops[scale_idx][crop_idx] 是 (batch_size, 3, 224, 224)
74
+ # 只需要将每个 tensor 移动到 device
75
+ crops_tens = [[t.to(device) for t in scale_crops] for scale_crops in crops]
76
+ features = model.get_features(img_tens).to(device)
77
+
78
+ y_pred.extend(model(crops_tens, features)[0].sigmoid().flatten().tolist())
79
+ y_true.extend(labels.flatten().tolist())
80
+ y_true = np.array(y_true)
81
+ y_pred_proba = np.array(y_pred) # 保留连续的概率值
82
+ y_pred_binary = np.where(y_pred_proba >= 0.5, 1, 0) # 二值化用于 acc 计算
83
+
84
+ # Get AP (使用连续概率值)
85
+ ap = average_precision_score(y_true, y_pred_proba)
86
+
87
+ # Get AUC (使用连续概率值)
88
+ auc = roc_auc_score(y_true, y_pred_proba)
89
+
90
+ # 计算其他指标 (使用二值化结果)
91
+ cm = confusion_matrix(y_true, y_pred_binary)
92
+ tp, fn, fp, tn = cm.ravel()
93
+ fnr = fn / (fn + tp)
94
+ fpr = fp / (fp + tn)
95
+ acc = accuracy_score(y_true, y_pred_binary)
96
+
97
+ # 计算 EER 和 ACC@EER
98
+ eer, eer_threshold = compute_eer(y_true, y_pred_proba)
99
+ acc_at_eer = compute_acc_at_eer(y_true, y_pred_proba, eer_threshold)
100
+
101
+ return acc, ap, auc, fpr, fnr, eer, acc_at_eer, y_true, y_pred, img_paths
102
+
103
+
104
+ if __name__ == "__main__":
105
+ parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
106
+ parser.add_argument("--real_list_path", type=str, default="./datasets/val/0_real")
107
+ parser.add_argument("--fake_list_path", type=str, default="./datasets/val/1_fake")
108
+ parser.add_argument("--max_sample", type=int, default=1000, help="max number of validate samples")
109
+ parser.add_argument("--batch_size", type=int, default=10)
110
+ parser.add_argument("--data_label", type=str, default="val")
111
+ parser.add_argument("--arch", type=str, default="CLIP:ViT-L/14")
112
+ parser.add_argument("--ckpt", type=str, default="./checkpoints/ckpt.pth")
113
+ parser.add_argument("--gpu", type=int, default=0)
114
+ parser.add_argument("--output_csv", type=str, default=None, help="Path to save inference results as CSV")
115
+
116
+ opt = parser.parse_args()
117
+
118
+ device = torch.device(f"cuda:{opt.gpu}" if torch.cuda.is_available() else "cpu")
119
+ print(f"Using cuda {opt.gpu} for inference.")
120
+
121
+ model = build_model(opt.arch)
122
+ state_dict = torch.load(opt.ckpt, map_location="cpu")
123
+ model.load_state_dict(state_dict["model"])
124
+ print("Model loaded.")
125
+ model.eval()
126
+ model.to(device)
127
+
128
+ dataset = AVLip(opt)
129
+ loader = data_loader = torch.utils.data.DataLoader(
130
+ dataset, batch_size=opt.batch_size, shuffle=False, # 改为 False 以保持顺序
131
+ collate_fn=custom_collate # 使用自定义 collate 函数
132
+ )
133
+ acc, ap, auc, fpr, fnr, eer, acc_at_eer, y_true, y_pred, img_paths = validate(model, loader, gpu_id=[opt.gpu])
134
+ print(f"acc: {acc} ap: {ap} auc: {auc} fpr: {fpr} fnr: {fnr} eer: {eer} acc@eer: {acc_at_eer}")
135
+
136
+ # 保存结果到 CSV
137
+ if opt.output_csv is not None:
138
+ print(f"Saving inference results to {opt.output_csv}...")
139
+
140
+ # 计算 EER 和对应的阈值
141
+ eer, eer_threshold = compute_eer(np.array(y_true), np.array(y_pred))
142
+ acc_at_eer = compute_acc_at_eer(np.array(y_true), np.array(y_pred), eer_threshold)
143
+
144
+ print(f"EER: {eer}, EER threshold: {eer_threshold}, ACC@EER: {acc_at_eer}")
145
+
146
+ # 准备数据
147
+ results = []
148
+ y_pred_proba = np.array(y_pred)
149
+ y_pred_binary = np.where(y_pred_proba >= 0.5, 1, 0)
150
+ y_pred_at_eer = (y_pred_proba >= eer_threshold).astype(int)
151
+
152
+ for i in range(len(y_true)):
153
+ result_dict = {
154
+ 'img_path': img_paths[i] if i < len(img_paths) else f'sample_{i}',
155
+ 'true_label': int(y_true[i]),
156
+ 'pred_prob': float(y_pred_proba[i]),
157
+ 'pred_label_05': int(y_pred_binary[i]),
158
+ 'pred_label_eer': int(y_pred_at_eer[i])
159
+ }
160
+ results.append(result_dict)
161
+
162
+ # 保存到 CSV
163
+ df = pd.DataFrame(results)
164
+ df.to_csv(opt.output_csv, index=False)
165
+ print(f"Results saved to {opt.output_csv}")
166
+
167
+ # 保存汇总统计到另一个文件
168
+ summary_path = opt.output_csv.replace('.csv', '_summary.csv')
169
+ summary = {
170
+ 'metric': ['acc', 'ap', 'auc', 'fpr', 'fnr', 'eer', 'acc_at_eer', 'eer_threshold'],
171
+ 'value': [acc, ap, auc, fpr, fnr, eer, acc_at_eer, eer_threshold]
172
+ }
173
+ df_summary = pd.DataFrame(summary)
174
+ df_summary.to_csv(summary_path, index=False)
175
+ print(f"Summary saved to {summary_path}")