Add files using upload-large-folder tool
Browse files- .gitignore +3 -0
- GUIDE.md +338 -0
- LipFD.yml +95 -0
- README.md +127 -0
- README_CONVERT.md +140 -0
- __pycache__/utils.cpython-310.pyc +0 -0
- __pycache__/validate.cpython-310.pyc +0 -0
- _diag_perturb.py +64 -0
- convert_ft_work.py +177 -0
- evaluate_robustness.py +621 -0
- evaluate_test.py +251 -0
- models/LipFD.py +42 -0
- models/__init__.py +28 -0
- models/clip_models.py +24 -0
- models/region_awareness.py +303 -0
- models/resnet.py +336 -0
- models/vision_transformer.py +481 -0
- models/vision_transformer_misc.py +163 -0
- models/vision_transformer_utils.py +549 -0
- options/base_options.py +108 -0
- options/test_options.py +11 -0
- options/train_options.py +21 -0
- plot_compare_with_lipfd.py +149 -0
- plot_robustness.py +219 -0
- preprocess.log +0 -0
- preprocess.py +125 -0
- preprocess_improved.py +258 -0
- requirements.txt +10 -0
- robustness/runs.json +0 -0
- robustness/runs.json.20260625_142029.bak +638 -0
- robustness/sweep.log +0 -0
- robustness/sweepv2.log +40 -0
- robustness/sweepv3.log +0 -0
- robustness/test_clean.json +314 -0
- robustnessv2/runs.json +638 -0
- robustnessv2/runs.json.20260625_212207.bak +321 -0
- robustnessv4/robustness_table.csv +30 -0
- robustnessv4/runs.json +0 -0
- robustnessv4/sweep.log +0 -0
- run_preprocess.sh +67 -0
- run_robustness.sh +54 -0
- run_robustness_v4.sh +50 -0
- run_robustnessv2.sh +54 -0
- split_dataset.log +0 -0
- split_dataset.py +193 -0
- train.log +1126 -0
- train.py +56 -0
- trainer/trainer.py +113 -0
- utils.py +10 -0
- validate.py +175 -0
.gitignore
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.DS_Store
|
| 2 |
+
__pycache__
|
| 3 |
+
.vscode/
|
GUIDE.md
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
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 |
+

|
| 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 |
+

|
| 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 |
+

|
| 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 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
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/ ({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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 @@
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|