Mengieong commited on
Commit
02e9762
·
verified ·
1 Parent(s): 10145b5

Upload 253 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. FAITH/.DS_Store +0 -0
  3. FAITH/BatchSampler.py +261 -0
  4. FAITH/README.md +205 -0
  5. FAITH/configs/r34.json +39 -0
  6. FAITH/configs/r50.json +39 -0
  7. FAITH/datasets/__init__.py +0 -0
  8. FAITH/datasets/__pycache__/__init__.cpython-36.pyc +0 -0
  9. FAITH/datasets/__pycache__/__init__.cpython-39.pyc +0 -0
  10. FAITH/datasets/__pycache__/add_noise.cpython-36.pyc +0 -0
  11. FAITH/datasets/__pycache__/add_noise.cpython-39.pyc +0 -0
  12. FAITH/datasets/__pycache__/compress.cpython-36.pyc +0 -0
  13. FAITH/datasets/__pycache__/compress.cpython-39.pyc +0 -0
  14. FAITH/datasets/__pycache__/dataset.cpython-36.pyc +0 -0
  15. FAITH/datasets/__pycache__/dataset.cpython-39.pyc +0 -0
  16. FAITH/datasets/add_noise.py +92 -0
  17. FAITH/datasets/compress.py +104 -0
  18. FAITH/datasets/dataset.py +209 -0
  19. FAITH/models/DCT.py +92 -0
  20. FAITH/models/FFT.py +193 -0
  21. FAITH/models/FrozenCLIPTextEncoder.py +104 -0
  22. FAITH/models/SeqFakeFormer.py +73 -0
  23. FAITH/models/__init__.py +0 -0
  24. FAITH/models/__pycache__/DCT.cpython-36.pyc +0 -0
  25. FAITH/models/__pycache__/FFT.cpython-36.pyc +0 -0
  26. FAITH/models/__pycache__/FrozenCLIPTextEncoder.cpython-36.pyc +0 -0
  27. FAITH/models/__pycache__/FrozenCLIPTextEncoder.cpython-39.pyc +0 -0
  28. FAITH/models/__pycache__/SeqFakeFormer.cpython-36.pyc +0 -0
  29. FAITH/models/__pycache__/SeqFakeFormer.cpython-39.pyc +0 -0
  30. FAITH/models/__pycache__/__init__.cpython-36.pyc +0 -0
  31. FAITH/models/__pycache__/__init__.cpython-39.pyc +0 -0
  32. FAITH/models/__pycache__/attention_layer.cpython-36.pyc +0 -0
  33. FAITH/models/__pycache__/attention_layer.cpython-39.pyc +0 -0
  34. FAITH/models/__pycache__/backbone.cpython-36.pyc +0 -0
  35. FAITH/models/__pycache__/backbone.cpython-39.pyc +0 -0
  36. FAITH/models/__pycache__/configuration.cpython-36.pyc +0 -0
  37. FAITH/models/__pycache__/configuration.cpython-39.pyc +0 -0
  38. FAITH/models/__pycache__/position_encoding.cpython-36.pyc +0 -0
  39. FAITH/models/__pycache__/position_encoding.cpython-39.pyc +0 -0
  40. FAITH/models/__pycache__/transformer_SECA.cpython-36.pyc +0 -0
  41. FAITH/models/__pycache__/transformer_SECA.cpython-39.pyc +0 -0
  42. FAITH/models/attention_layer.py +409 -0
  43. FAITH/models/backbone.py +121 -0
  44. FAITH/models/configuration.py +61 -0
  45. FAITH/models/dct_test.jpg +3 -0
  46. FAITH/models/position_encoding.py +85 -0
  47. FAITH/models/test.jpg +3 -0
  48. FAITH/models/transformer_SECA.py +630 -0
  49. FAITH/pytorch_wavelets/.travis.yml +14 -0
  50. FAITH/pytorch_wavelets/LICENSE +28 -0
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ FAITH/pytorch_wavelets/tests/cplx.mat filter=lfs diff=lfs merge=lfs -text
FAITH/.DS_Store ADDED
Binary file (10.2 kB). View file
 
FAITH/BatchSampler.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+ import pdb
3
+ import random
4
+ import numpy as np
5
+ import itertools
6
+ import torch
7
+ from torch.utils.data import Sampler
8
+
9
+ from datasets.dataset import SeqDeepFakeDataset
10
+ from models.configuration import Config
11
+
12
+ # class BalancedBatchSampler(Sampler):
13
+ # def __init__(self, dataset, batch_size):
14
+ # self.n_classes = 5
15
+ # self.batch_size = batch_size
16
+ # self.n_samples_per_class = self.batch_size // self.n_classes
17
+
18
+ # # 获取每个类别的样本索引
19
+ # self.class_indices = [[] for _ in range(self.n_classes)]
20
+
21
+ # for idx, (_, _, _, _, length) in enumerate(dataset):
22
+ # self.class_indices[length].append(idx)
23
+
24
+ # self.class_indices = [np.array(indices) for indices in self.class_indices]
25
+
26
+ # # 计算最大类别样本数确定epoch长度
27
+ # self.class_counts = [len(indices) for indices in self.class_indices]
28
+ # self.max_class_count = max(self.class_counts)
29
+ # self.num_batches = self.max_class_count // self.n_samples_per_class
30
+
31
+ # print(f"self.class_counts: {self.class_counts}")
32
+ # # print(self.max_class_count)
33
+ # print(f"self.num_batches: {self.num_batches}")
34
+
35
+ # def __iter__(self):
36
+ # # 每个epoch开始时打乱各类别样本顺序
37
+ # shuffled_indices = [indices.copy() for indices in self.class_indices]
38
+ # for arr in shuffled_indices:
39
+ # np.random.shuffle(arr)
40
+
41
+ # # 创建无限循环迭代器
42
+ # iterators = [itertools.cycle(arr) for arr in shuffled_indices]
43
+
44
+ # # 生成平衡批次
45
+ # for _ in range(self.num_batches):
46
+ # batch = []
47
+ # for class_idx in range(self.n_classes):
48
+ # batch.extend(
49
+ # [next(iterators[class_idx]) for _ in range(self.n_samples_per_class)]
50
+ # )
51
+ # np.random.shuffle(batch) # 打乱批次内顺序
52
+ # yield batch
53
+
54
+ # def __len__(self):
55
+ # return self.num_batches
56
+
57
+
58
+ # Deprecated
59
+ class EfficientBalancedBatchSampler(Sampler):
60
+ def __init__(self, dataset, batch_size, samples_per_class=None):
61
+ """
62
+ :param dataset: 包含targets属性的数据集
63
+ :param batch_size: 总批量大小,需能被类别数整除
64
+ :param samples_per_class: 每个类别的样本数, 自动计算如果为None
65
+ """
66
+ # self.labels = np.asarray(dataset.targets)
67
+ self.batch_size = batch_size
68
+
69
+ # 按类别组织索引
70
+ self.class_indices = defaultdict(list)
71
+ # for idx, label in enumerate(self.labels):
72
+ # self.class_indices[label].append(idx)
73
+
74
+ for idx, (_, _, _, _, length) in enumerate(dataset):
75
+ self.class_indices[length].append(idx)
76
+
77
+ self.classes = list(self.class_indices.keys())
78
+ self.num_classes = len(self.classes)
79
+
80
+ # 自动计算每个类别的样本数
81
+ if samples_per_class is None:
82
+ assert batch_size % self.num_classes == 0, "batch_size必须能被类别数整除"
83
+ self.samples_per_class = batch_size // self.num_classes
84
+ else:
85
+ self.samples_per_class = samples_per_class
86
+ assert batch_size == self.samples_per_class * self.num_classes
87
+
88
+ # 预计算每个类别的循环次数
89
+ self.class_repeats = self._calculate_repeats()
90
+
91
+ # 生成全局采样计划
92
+ self.sampling_plan = self._generate_sampling_plan()
93
+
94
+ def _calculate_repeats(self):
95
+ """计算每个类别需要的重复次数"""
96
+ repeats = {}
97
+ max_batches = 0
98
+ for cls in self.classes:
99
+ n_samples = len(self.class_indices[cls])
100
+ n_batches = (n_samples + self.samples_per_class - 1) // self.samples_per_class
101
+ max_batches = max(max_batches, n_batches)
102
+
103
+ for cls in self.classes:
104
+ n_samples = len(self.class_indices[cls])
105
+ total_needed = max_batches * self.samples_per_class
106
+ repeats[cls] = (total_needed + n_samples - 1) // n_samples
107
+ return repeats
108
+
109
+ def _generate_sampling_plan(self):
110
+ """生成全局采样索引矩阵"""
111
+ # 预分配内存
112
+ sampling_matrix = np.zeros((self.num_classes,
113
+ max(self.class_repeats.values()) * self.samples_per_class),
114
+ dtype=np.int64)
115
+
116
+ for i, cls in enumerate(self.classes):
117
+ indices = np.array(self.class_indices[cls])
118
+ np.random.shuffle(indices) # 初始打乱
119
+
120
+ # 生成重复索引块
121
+ repeated = np.tile(indices, self.class_repeats[cls])
122
+ np.random.shuffle(repeated) # 再次打乱保证随机性
123
+
124
+ # 截取所需长度
125
+ required_length = max(self.class_repeats.values()) * self.samples_per_class
126
+ sampling_matrix[i] = repeated[:required_length]
127
+
128
+ return sampling_matrix.reshape(self.num_classes, -1, self.samples_per_class)
129
+
130
+ def __iter__(self):
131
+ # 转置维度:类别 × 总批次 → 总批次 × 类别
132
+ batch_plan = self.sampling_plan.transpose(1, 0, 2)
133
+
134
+ # 打乱批次顺序
135
+ np.random.shuffle(batch_plan)
136
+
137
+ # 生成最终批次
138
+ for batch in batch_plan:
139
+ # 合并所有类别的样本并打乱顺序
140
+ combined = batch.flatten()
141
+ np.random.shuffle(combined)
142
+ yield combined.tolist()
143
+
144
+ def __len__(self):
145
+ return self.sampling_plan.shape[1]
146
+
147
+
148
+ '''
149
+ Uneven sample distribution will affect the performance of the model.
150
+ For example, the model has higher accuracy for shorter samples.
151
+ A uniform sampler ensures that the samples in each batch are evenly distributed.
152
+ e.g. sequence length 0:1:2:3:4 = 1:1:1:1:1
153
+ '''
154
+ class BalancedBatchSampler(Sampler):
155
+ def __init__(self, A_indices, B_indices, C_indices, D_indices, E_indices, batch_size, epoch_length, rank = 0, world_size = 1):
156
+ """
157
+ A_indices: 类别A的样本索引列表
158
+ B_indices: 类别B的样本索引列表
159
+ C_indices: 类别C的样本索引列表
160
+ D_indices: 类别D的样本索引列表
161
+ E_indices: 类别E的样本索引列表
162
+ batch_size: 每个批次的大小, 必须能被5整除
163
+ epoch_length: 每个epoch的批次数量
164
+ """
165
+ super().__init__(None)
166
+ self.A = A_indices[rank::world_size]
167
+ self.B = B_indices[rank::world_size]
168
+ self.C = C_indices[rank::world_size]
169
+ self.D = D_indices[rank::world_size]
170
+ self.E = E_indices[rank::world_size]
171
+
172
+ random.shuffle(self.A)
173
+ random.shuffle(self.B)
174
+ random.shuffle(self.C)
175
+ random.shuffle(self.D)
176
+ random.shuffle(self.E)
177
+
178
+ self.batch_size = batch_size
179
+ self.n = batch_size // 5
180
+ self.epoch_length = epoch_length
181
+ self.epoch = 0
182
+ self.rank = rank
183
+ self.world_size = world_size
184
+
185
+ assert batch_size % 5 == 0, "batch_size必须能被5整除"
186
+
187
+ def set_epoch(self, epoch):
188
+ self.epoch = epoch
189
+ random.seed(epoch + self.rank)
190
+ torch.manual_seed(epoch + self.rank)
191
+
192
+ def __iter__(self):
193
+ # random.seed(self.epoch)
194
+
195
+ # 生成指定数量的平衡批次
196
+ for i in range(self.epoch_length):
197
+ # 从每个类别中随机选择n个样本(不允许重复)
198
+ # batch_A = random.choices(self.A, k=self.n)
199
+ # batch_B = random.choices(self.B, k=self.n)
200
+ # batch_C = random.choices(self.C, k=self.n)
201
+ # batch_D = random.choices(self.D, k=self.n)
202
+ # batch_E = random.choices(self.E, k=self.n)
203
+
204
+ batch_A = self.A[self.n * i : self.n * (i + 1)]
205
+ batch_B = self.B[self.n * i : self.n * (i + 1)]
206
+ batch_C = self.C[self.n * i : self.n * (i + 1)]
207
+ batch_D = self.D[self.n * i : self.n * (i + 1)]
208
+ batch_E = self.E[self.n * i : self.n * (i + 1)]
209
+
210
+ # 合并并打乱顺序
211
+ combined = batch_A + batch_B + batch_C + batch_D + batch_E
212
+ random.shuffle(combined)
213
+
214
+ yield combined
215
+
216
+ def __len__(self):
217
+ return self.epoch_length
218
+
219
+
220
+ # cfg = Config('./configs/r50.json')
221
+
222
+ # dataset = SeqDeepFakeDataset(
223
+ # cfg=cfg,
224
+ # mode="train",
225
+ # data_root='data',
226
+ # dataset_name='SD3'
227
+ # )
228
+
229
+ # # sampler = BalancedBatchSampler(
230
+ # # dataset,
231
+ # # 40
232
+ # # )
233
+
234
+ # # sampler = EfficientBalancedBatchSampler(
235
+ # # dataset,
236
+ # # 40,
237
+ # # 8
238
+ # # )
239
+
240
+ # sampler = BalancedBatchSampler(
241
+ # list(range(0, 16036)),
242
+ # list(range(16036, 37897)),
243
+ # list(range(37897, 57159)),
244
+ # list(range(57159, 73044)),
245
+ # list(range(73044, 80000)),
246
+ # 40,
247
+ # 2000
248
+ # )
249
+
250
+ # dataloader = torch.utils.data.DataLoader(
251
+ # dataset,
252
+ # batch_sampler= sampler,
253
+ # pin_memory=True,
254
+ # # num_workers=8
255
+ # )
256
+
257
+ # print(len(dataloader))
258
+
259
+ # for steps, (_, _, caps, _, length) in enumerate(dataloader): # masks.shape: [bs, 512, 512]
260
+ # print(caps)
261
+ # pdb.set_trace()
FAITH/README.md ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- <div align="center">
2
+
3
+ <h1>SeqDeepFake: Detecting and Recovering Sequential DeepFake Manipulation</h1>
4
+
5
+ <div>
6
+ <a href='https://rshaojimmy.github.io/' target='_blank'>Rui Shao</a>,
7
+ <a href='https://tianxingwu.github.io/' arget='_blank'>Tianxing Wu</a>,
8
+ <a href='https://liuziwei7.github.io/' target='_blank'>Ziwei Liu</a>
9
+ </div>
10
+ <div>
11
+ S-Lab, Nanyang Technological University&emsp;
12
+ </div>
13
+
14
+ <h4 align="center">
15
+ <a href="https://rshaojimmy.github.io/Projects/SeqDeepFake" target='_blank'>[Project Page]</a> |
16
+ <a href="https://arxiv.org/pdf/2207.02204.pdf" target='_blank'>[Paper]</a> |
17
+ <a href="https://arxiv.org/pdf/2309.14991.pdf" target='_blank'>[Extension Paper]</a> |
18
+ <a href="https://huggingface.co/datasets/rshaojimmy/Seq-DeepFake/tree/main" target='_blank'>[Dataset]</a>
19
+ </h4>
20
+
21
+ <img src='./figs/SeqDeepFake.gif' width='90%'>
22
+
23
+ </div>
24
+
25
+ ## Updates
26
+ - [02/2024] Dataset link has been updated with hugginface.
27
+ - [09/2023] Arxiv extension paper released.
28
+ - [07/2022] Pretrained models are uploaded.
29
+ - [07/2022] Project page and dataset are released.
30
+ - [07/2022] Code is released.
31
+
32
+ ## Introduction
33
+ This is the official implementation of *Detecting and Recovering Sequential DeepFake Manipulation*. We introduce a novel research problem: Detecting Sequential DeepFake Manipulation (**Seq-DeepFake**), which focus on detecting the sequences of multi-step facial manipulations. To faciliatate the study of Seq-Deepfake, we provide a large-scale Sequential Deepfake Dataset, and propose a concise yet effective Seq-DeepFake Transformer (**SeqFakeFormer**).
34
+
35
+ The framework of the proposed method:
36
+
37
+ <div align="center">
38
+ <img src='./figs/SeqFakeFormer.png' width='100%'>
39
+ </div>
40
+
41
+
42
+
43
+
44
+ ## Installation
45
+
46
+ ### Download
47
+ ```
48
+ git clone https://github.com/rshao/SeqDeepFake.git
49
+ cd SeqDeepFake
50
+ ```
51
+
52
+
53
+ ### Environment
54
+ We recommend using Anaconda to manage the python environment:
55
+ ```
56
+ conda create -n seqdeepfake python=3.6
57
+ conda activate seqdeepfake
58
+ conda install -c pytorch pytorch=1.6.0 torchvision=0.7.0 cudatoolkit==10.1.243
59
+ conda install pandas
60
+ conda install tqdm
61
+ conda install pillow
62
+ pip install tensorboard==2.4.1
63
+ ```
64
+
65
+
66
+ ## Dataset Preparation
67
+
68
+ ### A brief introduction
69
+ We contribute the first large-scale Sequential DeepFake Dataset, **Seq-Deepfake**, including **~85k** sequentially manipulated face images, each annotated with its ground-truth manipulation sequence.
70
+
71
+ The images are generated based on the following two different facial manipulation methods, with **28** / **26** types of manipulation sequences (including original), repectively. The lengths of all manipulation sequences range from 1~5.
72
+
73
+ - Sequential facial components manipulation (based on [CelebAMask-HQ](http://mmlab.ie.cuhk.edu.hk/projects/CelebA/CelebAMask_HQ.html) and [StyleMapGAN](https://arxiv.org/abs/2104.14754))
74
+ - Sequential facial attributes manipulation (based on [FFHQ](https://github.com/NVlabs/ffhq-dataset) and [Talk-To-Edit](https://arxiv.org/abs/2109.04425))
75
+
76
+ Here are some sample images and statistics:
77
+ <div align="center">
78
+ <img src='./figs/dataset.png' width='90%'>
79
+ </div>
80
+
81
+ ### Annotations
82
+ Each image in the dataset is annotated with a list of length 5, indicating the ground-truth manipulation sequence. The labels in the sequence are defined as follows:
83
+
84
+ For Sequential facial components manipulation:
85
+
86
+ ```
87
+ 0: 'NA', 1: 'nose', 2: 'eye', 3: 'eyebrow', 4: 'lip', 5: 'hair'
88
+
89
+ Note: 'NA' means no manipulation is taken in this step.
90
+ ```
91
+
92
+ For Sequential facial attributes manipulation:
93
+ ```
94
+ 0: 'NA', 1: 'Bangs', 2: 'Eyeglasses', 3: 'Beard', 4: 'Smiling', 5: 'Young'
95
+
96
+ Note: 'NA' means no manipulation is taken in this step.
97
+ ```
98
+ Note that label `0` serves as the placeholder for sequential manipulations shorter than 5 steps. For example, the annotation for manipulation sequence `nose-eye-lip` would be: `[1, 2, 4, 0, 0]`. Original images are annotated with `[0, 0, 0, 0, 0]`.
99
+
100
+
101
+ ### Prepare data
102
+ You can download the Seq-Deepfake dataset through this link: <a href="https://lifehkbueduhk-my.sharepoint.com/:f:/g/personal/16483782_life_hkbu_edu_hk/Evp-uhtWYMBLi9G9JlPcKCEBewkMqPCU69L4Kf29qDQaOw?e=G9JaRm" target='_blank'>[Dataset]</a>
103
+
104
+ After unzip all sub files, the structure of the dataset should be as follows:
105
+
106
+ ```
107
+ ./
108
+ ├── facial_attributes
109
+ │ ├── annotations
110
+ │ | ├── train.csv
111
+ │ | ├── test.csv
112
+ │ | └── val.csv
113
+ │ └── images
114
+ │ ├── train
115
+ │ │ ├── Bangs-Eyeglasses-Smiling-Young
116
+ │ │ | ├── xxxxxx.jpg
117
+ | | | ...
118
+ | | | └── xxxxxx.jpg
119
+ | | ...
120
+ │ │ ├── Young-Smiling-Eyeglasses
121
+ │ │ | ├── xxxxxx.jpg
122
+ | | | ...
123
+ | | | └── xxxxxx.jpg
124
+ │ │ └── original
125
+ │ │ ├── xxxxxx.jpg
126
+ | | ...
127
+ | | └── xxxxxx.jpg
128
+ │ ├── test
129
+ │ │ % the same structure as in train
130
+ │ └── val
131
+ │ % the same structure as in train
132
+ └── facial_components
133
+ ├── annotations
134
+ | ├── train.csv
135
+ | ├── test.csv
136
+ | └── val.csv
137
+ └── images
138
+ ├── train
139
+ │ ├── eyebrow-eye-hair-nose-lip
140
+ │ | ├── xxxxxx.jpg
141
+ | | ...
142
+ | | └── xxxxxx.jpg
143
+ | ...
144
+ │ ├── nose-eyebrow-lip-eye-hair
145
+ │ | ├── xxxxxx.jpg
146
+ | | ...
147
+ | | └── xxxxxx.jpg
148
+ │ └── original
149
+ │ ├── xxxxxx.jpg
150
+ | ...
151
+ | └── xxxxxx.jpg
152
+ ├── test
153
+ │ % the same structure as in train
154
+ └── val
155
+ % the same structure as in train
156
+ ```
157
+
158
+
159
+ ## Training
160
+
161
+ ### Single-GPU
162
+
163
+ Modify `train.sh` and run:
164
+ ```
165
+ sh train.sh
166
+ ```
167
+
168
+ Please refer to the following instructions about some arguments:
169
+
170
+ | Args | Description
171
+ | :-------- | :--------
172
+ | CONFIG | Path of the network and optimization configuration file.
173
+ | DATA_DIR | Directory to the downloaded dataset.
174
+ | DATASET_NAME | Name of the selected manipulation type. Choose from 'facial_components' and 'facial_attributes'.
175
+ | RESULTS_DIR | Directory to save logs and checkpoints.
176
+
177
+
178
+ You can change the network and optimization configurations by adding new configuration files under the directory `./configs/`.
179
+
180
+
181
+ ### Multiple-GPUs (Slurm)
182
+
183
+ We also provide slurm script that supports multiple GPUs training:
184
+ ```
185
+ sh train_slurm.sh
186
+ ```
187
+ where `PARTITION` and `NODE` should be modified according to your own environment. The number of GPUs to be used can be set through the `NUM_GPU` argument.
188
+
189
+ ## Testing
190
+ Modify `test.sh` and run:
191
+ ```
192
+ sh test.sh
193
+ ```
194
+
195
+ For the arguments in `test.sh`, please refer to the training instructions above, plus the following ones:
196
+ | Args | Description
197
+ | :--- | :----------
198
+ | TEST_TYPE | The evaluation metrics to use. Choose from 'fixed' and 'adaptive'.
199
+ | LOG_NAME | Should be set according to the log_name of your trained checkpoint to be tested.
200
+
201
+ We also provide slurm script for testing:
202
+
203
+ ```
204
+ sh test_slurm.sh
205
+ ```
FAITH/configs/r34.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backbone":{
3
+ "network": "resnet34",
4
+ "position_embedding": "sine",
5
+ "Frozen_BatchNorm2d": false
6
+ },
7
+ "optimizer":{
8
+ "batch_size": 32,
9
+ "lr_backbone": 1e-4,
10
+ "lr": 1e-3,
11
+ "epochs": 170,
12
+ "warmup": true,
13
+ "warmup_epochs": 20,
14
+ "lr_milestones": [70,120],
15
+ "start_epoch": 0,
16
+ "weight_decay": 1e-4,
17
+ "clip_max_norm": 0.1
18
+ },
19
+ "transformer":{
20
+ "SOS_token_id": 0,
21
+ "EOS_token_id": 6,
22
+ "PAD_token_id": 7,
23
+ "smooth": 4,
24
+ "dynamic_scale": "type3",
25
+ "max_position_embeddings": 6,
26
+ "vocab_size": 8,
27
+ "layer_norm_eps": 1e-12,
28
+ "dropout": 0.1,
29
+ "hidden_dim": 256,
30
+ "enc_layers": 2,
31
+ "dec_layers": 2,
32
+ "dim_feedforward": 512,
33
+ "nheads": 4,
34
+ "pre_norm": true
35
+ },
36
+ "dataset":{
37
+ "imgsize": 256
38
+ }
39
+ }
FAITH/configs/r50.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backbone":{
3
+ "network": "resnet50",
4
+ "position_embedding": "sine",
5
+ "Frozen_BatchNorm2d": false
6
+ },
7
+ "optimizer":{
8
+ "batch_size": 48,
9
+ "lr_backbone": 1e-4,
10
+ "lr": 1e-3,
11
+ "epochs": 150,
12
+ "warmup": true,
13
+ "warmup_epochs": 25,
14
+ "lr_milestones": [50,75,100],
15
+ "start_epoch": 0,
16
+ "weight_decay": 1e-4,
17
+ "clip_max_norm": 0.1
18
+ },
19
+ "transformer":{
20
+ "SOS_token_id": 0,
21
+ "EOS_token_id": 7,
22
+ "PAD_token_id": 8,
23
+ "smooth": 4,
24
+ "dynamic_scale": "type3",
25
+ "max_position_embeddings": 5,
26
+ "vocab_size": 9,
27
+ "layer_norm_eps": 1e-12,
28
+ "dropout": 0.1,
29
+ "hidden_dim": 512,
30
+ "enc_layers": 2,
31
+ "dec_layers": 2,
32
+ "dim_feedforward": 512,
33
+ "nheads": 4,
34
+ "pre_norm": true
35
+ },
36
+ "dataset":{
37
+ "imgsize": 512
38
+ }
39
+ }
FAITH/datasets/__init__.py ADDED
File without changes
FAITH/datasets/__pycache__/__init__.cpython-36.pyc ADDED
Binary file (138 Bytes). View file
 
FAITH/datasets/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (146 Bytes). View file
 
FAITH/datasets/__pycache__/add_noise.cpython-36.pyc ADDED
Binary file (973 Bytes). View file
 
FAITH/datasets/__pycache__/add_noise.cpython-39.pyc ADDED
Binary file (985 Bytes). View file
 
FAITH/datasets/__pycache__/compress.cpython-36.pyc ADDED
Binary file (1.94 kB). View file
 
FAITH/datasets/__pycache__/compress.cpython-39.pyc ADDED
Binary file (1.93 kB). View file
 
FAITH/datasets/__pycache__/dataset.cpython-36.pyc ADDED
Binary file (3.99 kB). View file
 
FAITH/datasets/__pycache__/dataset.cpython-39.pyc ADDED
Binary file (4 kB). View file
 
FAITH/datasets/add_noise.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import cv2
2
+ # import numpy as np
3
+
4
+ # def add_salt_pepper_noise(image, prob):
5
+ # """
6
+ # 为图像添加椒盐噪声
7
+ # :param image: 输入图像(彩色或灰度)
8
+ # :param prob: 噪声比例(总像素点的比例)
9
+ # :return: 带噪声的图像
10
+ # """
11
+ # output = image.copy()
12
+ # # 获取图像维度
13
+ # if len(image.shape) == 3:
14
+ # row, col, ch = image.shape
15
+ # else:
16
+ # row, col = image.shape
17
+ # ch = 1
18
+
19
+ # # 生成随机矩阵
20
+ # rnd = np.random.rand(row, col)
21
+ # # 盐噪声(白色)
22
+ # salt = rnd < prob / 2
23
+ # # 椒噪声(黑色)
24
+ # pepper = (rnd >= prob / 2) & (rnd < prob)
25
+
26
+ # # 应用噪声
27
+ # if ch == 1:
28
+ # output[salt] = 255
29
+ # output[pepper] = 0
30
+ # else:
31
+ # for c in range(ch):
32
+ # output[:, :, c][salt] = 255
33
+ # output[:, :, c][pepper] = 0
34
+ # return output
35
+
36
+
37
+
38
+ # if __name__ == "__main__":
39
+ # # 设置随机种子以确保结果可重复
40
+ # np.random.seed(42)
41
+
42
+ # # 读取图像
43
+ # image = cv2.imread('../../../ultraedit/UltraEdit/sequential_deepfake_dataset/0/50.jpg')
44
+
45
+ # # 添加不同强度的噪声
46
+ # noisy_small = add_salt_pepper_noise(image, 0.05) # 少量噪声(5%)
47
+ # noisy_medium = add_salt_pepper_noise(image, 0.1) # 中等噪声(10%)
48
+ # noisy_large = add_salt_pepper_noise(image, 0.2) # 大量噪声(20%)
49
+
50
+ # # 保存结果
51
+ # cv2.imwrite('noisy_small_sp.jpg', noisy_small)
52
+ # cv2.imwrite('noisy_medium_sp.jpg', noisy_medium)
53
+ # cv2.imwrite('noisy_large_sp.jpg', noisy_large)
54
+
55
+ from PIL import Image
56
+ import numpy as np
57
+
58
+ def add_gaussian_noise(image_path: str, sigma: float) -> Image.Image:
59
+ """
60
+ 为图像添加高斯噪声 (PIL实现版)
61
+ :param image_path: 输入图像路径
62
+ :param sigma: 噪声的标准差,控制噪声强度
63
+ :return: 带噪声的PIL.Image对象
64
+ """
65
+ # 打开图像并转换为numpy数组
66
+ img = Image.open(image_path)
67
+ img_array = np.array(img)
68
+
69
+ # 生成高斯噪声 (与图像形状相同)
70
+ noise = np.random.normal(0, sigma, img_array.shape).astype(np.int32)
71
+
72
+ # 添加噪声并截断到有效范围
73
+ noisy_array = np.clip(img_array.astype(np.int32) + noise, 0, 255).astype(np.uint8)
74
+
75
+ # 将numpy数组转换回Image对象
76
+ return Image.fromarray(noisy_array)
77
+
78
+
79
+ if __name__ == "__main__":
80
+ image_path = "../../../ultraedit/UltraEdit/sequential_deepfake_dataset/0/50.jpg" # 输入图像路径
81
+ # 使用示例
82
+ # noisy_small = add_gaussian_noise(image_path, sigma=20) # 少量噪声
83
+ # noisy_medium = add_gaussian_noise(image_path, sigma=30) # 中等噪声
84
+ noisy_large = add_gaussian_noise(image_path, sigma=40) # 大量噪声
85
+
86
+ print(type(noisy_large))
87
+ print(noisy_large.size)
88
+
89
+ # # 保存结果
90
+ # noisy_small.save("noisy_small.jpg")
91
+ # noisy_medium.save("noisy_medium.jpg")
92
+ # noisy_large.save("noisy_large.jpg")
FAITH/datasets/compress.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from PIL import Image
3
+ from io import BytesIO
4
+ # from torchvision import transforms
5
+
6
+
7
+ def compress_image(input_path, target_ratio, output_path=""):
8
+ """
9
+ 压缩图像到指定的压缩率
10
+ :param input_path: 输入图像路径
11
+ :param output_path: 输出图像路径
12
+ :param target_ratio: 目标压缩率(例如0.25表示25%)
13
+ """
14
+ # 获取原始文件大小
15
+ original_size = os.path.getsize(input_path)
16
+ target_size = original_size * target_ratio
17
+
18
+ # 打开图像并转换为RGB模式(避免透明通道问题)
19
+ img = Image.open(input_path)
20
+ if img.mode in ('RGBA', 'LA', 'P'):
21
+ img = img.convert('RGB')
22
+
23
+ # 寻找最佳质量参数
24
+ best_quality = find_optimal_quality(img, target_size)
25
+
26
+ # 将压缩结果保存到内存缓冲区
27
+ buffer = BytesIO()
28
+ img.save(buffer, format='JPEG', quality=best_quality, optimize=True)
29
+ # compressed_size = buffer.tell() # 获取当前缓冲区大小
30
+
31
+ # 从缓冲区创建新的Image对象
32
+ buffer.seek(0) # 重置指针位置
33
+ compressed_img = Image.open(buffer)
34
+
35
+ # # 保存压缩后的图像
36
+ # img.save(output_path, format='JPEG', quality=best_quality, optimize=True)
37
+ # compressed_size = os.path.getsize(output_path)
38
+
39
+ # 计算实际压缩率
40
+ # achieved_ratio = compressed_size / original_size
41
+
42
+ # trans = transforms.Compose([
43
+ # transforms.Resize(512),
44
+ # transforms.ToTensor(),
45
+ # transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
46
+ # ])
47
+
48
+ # compressed_img = trans(compressed_img)
49
+
50
+ # print(type(compressed_img))
51
+ # print(compressed_img.shape)
52
+ # print(f"输入文件: {input_path}")
53
+ # print(f"输入文件大小: {original_size}")
54
+ # print(f"目标压缩率: {target_ratio * 100}%")
55
+ # print(f"实际压缩率: {achieved_ratio * 100:.2f}%")
56
+ # print(f"使用的质量参数: {best_quality}")
57
+ # # print(f"输出文件: {output_path}")
58
+ # print(f"输出文件大小: {compressed_size}\n")
59
+
60
+ return compressed_img
61
+
62
+
63
+ def find_optimal_quality(img, target_size, max_iter=20):
64
+ """
65
+ 使用二分查找寻找最接近目标大小的JPEG质量参数
66
+ :param img: PIL图像对象
67
+ :param target_size: 目标文件大小(字节)
68
+ :param max_iter: 最大迭代次数
69
+ :return: 最佳质量参数(1-95)
70
+ """
71
+ low, high = 1, 95
72
+ best_quality = 95
73
+ best_diff = float('inf')
74
+
75
+ for _ in range(max_iter):
76
+ mid = (low + high) // 2
77
+ buffer = BytesIO()
78
+ img.save(buffer, format='JPEG', quality=mid, optimize=True)
79
+ current_size = buffer.tell()
80
+ current_diff = current_size - target_size
81
+
82
+ # 更新最佳质量参数
83
+ if abs(current_diff) < best_diff:
84
+ best_diff = abs(current_diff)
85
+ best_quality = mid
86
+
87
+ # 调整二分查找区间
88
+ if current_size < target_size:
89
+ low = mid + 1 # 需要更高的质量以增大文件
90
+ else:
91
+ high = mid - 1 # 需要更低的质量以减小文件
92
+
93
+ if low > high:
94
+ break
95
+
96
+ return best_quality
97
+
98
+ # 示例用法
99
+ if __name__ == "__main__":
100
+ input_image = "../../../ultraedit/UltraEdit/sequential_deepfake_dataset/87739/30_10_21_62.jpg" # 替换为你的输入图片路径
101
+ compress_image(input_image, "../compressed_10.jpg", 0.1)
102
+ compress_image(input_image, "../compressed_25.jpg", 0.25)
103
+ compress_image(input_image, "../compressed_50.jpg", 0.5)
104
+ compress_image(input_image, "../compressed_75.jpg", 0.75)
FAITH/datasets/dataset.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.utils.data import Dataset
3
+ import numpy as np
4
+ import os
5
+ import os.path
6
+ from PIL import Image
7
+ # import pandas as pd
8
+ from torchvision import transforms
9
+ from tools.utils import nested_tensor_from_tensor_list
10
+ from .compress import compress_image
11
+ from .add_noise import add_gaussian_noise
12
+
13
+ # def read_data(file, root = None):
14
+ # # info = pd.read_csv(file)
15
+ # # img_list = info['file_path'].tolist()
16
+ # # label_list = info['label'].tolist()
17
+
18
+ # # f = open("./test.txt", "w")
19
+ # # for i in range(len(img_list)):
20
+ # # f.write(img_list[i] + ";" + label_list[i])
21
+ # # # f.write(label_list[i])
22
+ # # f.write('\n')
23
+ # # f.close()
24
+
25
+ # dataset = []
26
+
27
+ # # img_list, label_list = [], []
28
+
29
+ # img_list_different_length = [[], [], [], [], []]
30
+ # label_list_different_length = [[], [], [], [], []]
31
+ # # length_list_different_length = [[], [], [], [], []]
32
+
33
+ # with open(file, "r") as f:
34
+ # for line in f:
35
+ # t = line.split(";")
36
+ # # img = t[0]
37
+ # label_list_split = t[1].split(',')
38
+ # label = [int(label_list_split[0][1]), int(label_list_split[1][1]), int(label_list_split[2][1]), int(label_list_split[3][1])]
39
+ # # print(label)
40
+ # if 0 in label:
41
+ # index = label.index(0)
42
+ # else:
43
+ # index = 4
44
+
45
+ # if root:
46
+ # t[0] = os.path.join(root, t[0]) # from relative path to absolute path
47
+
48
+ # # if ("val" in file or "test" in file):
49
+ # if 1:
50
+ # img_list_different_length[index].append(t[0])
51
+ # label_list_different_length[index].append(label)
52
+ # # else:
53
+ # # img_list.append(t[0])
54
+ # # label_list.append(label)
55
+ # # dataset.append((t[0], label, index))
56
+
57
+ # if ("val" in file or "test" in file):
58
+ # min_count = min(len(arr) for arr in label_list_different_length)
59
+ # for i in range(5):
60
+ # for j in range(min_count):
61
+ # dataset.append((img_list_different_length[i][j], label_list_different_length[i][j]))
62
+ # else:
63
+ # for i in range(5):
64
+ # for j in range(len(label_list_different_length[i])):
65
+ # dataset.append((img_list_different_length[i][j], label_list_different_length[i][j]))
66
+ # # print(len(dataset))
67
+ # # img_list = img_list + img_list_different_length[i][:min_count + 1]
68
+ # # label_list = label_list + label_list_different_length[i][:min_count + 1]
69
+
70
+ # # # with open(file.replace("csv", "txt"), "r") as f:
71
+ # # with open(file, "r") as f:
72
+ # # for line in f:
73
+ # # t = line.split(";")
74
+ # # img_list.append(t[0])
75
+ # # label_list.append(t[1])
76
+
77
+ # # return img_list, label_list, length_list
78
+ # return dataset
79
+
80
+
81
+ def read_data(file, root=None):
82
+ dataset = []
83
+ # img_list, label_list = [], []
84
+
85
+ with open(file, "r") as f:
86
+ for line in f:
87
+ t = line.split(";")
88
+ dataset.append((t[0][3:].replace("sequential_deepfake_dataset", "SEED"), t[1]))
89
+
90
+ return dataset
91
+
92
+
93
+ def make_dataset(csv_file, root=None):
94
+ dataset = []
95
+
96
+ imgs, labels = read_data(csv_file)
97
+
98
+ for i in range(len(imgs)):
99
+ # for i in range(1000):
100
+ # if root:
101
+ # imgs[i] = os.path.join(root, imgs[i]) # from relative path to absolute path
102
+ if 0 in labels[i]:
103
+ length = labels[i].index(0)
104
+ else:
105
+ length = 4
106
+ dataset.append((imgs[i], labels[i], length))
107
+ # print(dataset)
108
+ return dataset
109
+
110
+
111
+ def create_train_transforms(image_size):
112
+ return transforms.Compose([
113
+ transforms.Resize(image_size),
114
+ transforms.ColorJitter(brightness=[0.5, 1.3], contrast=[
115
+ 0.8, 1.5], saturation=[0.2, 1.5]), # 修改图像的亮度、对比度和饱和度
116
+ transforms.RandomHorizontalFlip(), # 按照概率p水平翻转图像
117
+ transforms.ToTensor(),
118
+ transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
119
+ ])
120
+
121
+
122
+ def create_val_transforms(image_size):
123
+ return transforms.Compose([
124
+ transforms.Resize(image_size),
125
+ transforms.ToTensor(),
126
+ transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
127
+ ])
128
+
129
+
130
+ class SeqDeepFakeDataset(Dataset):
131
+
132
+ def __init__(self,
133
+ cfg=None,
134
+ data_root=None,
135
+ mode="train",
136
+ dataset_name=None
137
+ ):
138
+ super().__init__()
139
+ self.mode = mode
140
+ self.cfg = cfg
141
+ if self.mode == "train":
142
+ self.transforms = create_train_transforms(cfg.imgsize)
143
+ elif self.mode in ["val", "test"]:
144
+ self.transforms = create_val_transforms(cfg.imgsize)
145
+ else:
146
+ raise ValueError(f"WRONG INPUT MODE: {self.mode}!")
147
+
148
+ self.data = read_data(os.path.join(data_root, f"{dataset_name}/{mode}.txt"), root=data_root)
149
+
150
+ self.SOS_token_id = cfg.SOS_token_id
151
+ self.EOS_token_id = cfg.EOS_token_id
152
+ self.PAD_token_id = cfg.PAD_token_id
153
+
154
+ def __getitem__(self, index: int):
155
+ img_path, label = self.data[index]
156
+ if self.mode in ["train"]:
157
+ label_list_split = label.split(',')
158
+
159
+ label_list = [int(label_list_split[0][1]), int(label_list_split[1][1]), int(label_list_split[2][1]), int(label_list_split[3][1])]
160
+
161
+ caption = np.array(label_list)
162
+
163
+ if np.count_nonzero(caption) == 0:
164
+ caption_mask = (1-np.array([1, 1, 0, 0, 0, 0])).astype(bool)
165
+ caption = np.insert(caption, [0, 0], [self.SOS_token_id, self.EOS_token_id])
166
+ caption[np.where(caption_mask==True)] = self.PAD_token_id
167
+
168
+ elif np.count_nonzero(caption) == len(caption):
169
+ caption_mask = (1-np.array([1, 1, 1, 1, 1, 1])).astype(bool)
170
+ caption = np.insert(caption, [0, 4], [self.SOS_token_id, self.EOS_token_id])
171
+ else:
172
+ first_zero_idx = np.where(caption==0)[0][0]
173
+ caption = np.insert(caption, [0, first_zero_idx], [self.SOS_token_id, self.EOS_token_id])
174
+ EOS_idx = np.where(caption==self.EOS_token_id)[0][0]
175
+ caption_mask = (1-np.pad(np.ones(EOS_idx+1), (0, len(caption)-(EOS_idx+1)))).astype(bool)
176
+ caption[np.where(caption_mask==True)] = self.PAD_token_id
177
+
178
+ image = Image.open(img_path).convert('RGB')
179
+ if self.transforms:
180
+ image = self.transforms(image)
181
+
182
+ image = nested_tensor_from_tensor_list(self.cfg.imgsize, image.unsqueeze(0))
183
+
184
+ return image.tensors.squeeze(0), image.mask.squeeze(0), caption, caption_mask
185
+ elif self.mode in ["val"]:
186
+ label_list_split = label.split(',')
187
+ label_list = [int(label_list_split[0][1]), int(label_list_split[1][1]), int(label_list_split[2][1]), int(label_list_split[3][1])]
188
+
189
+ image = Image.open(img_path).convert('RGB')
190
+ if self.transforms:
191
+ image = self.transforms(image)
192
+
193
+ return image, torch.FloatTensor(label_list), img_path
194
+ elif self.mode in ["test"]:
195
+ label_list_split = label.split(',')
196
+ label_list = [int(label_list_split[0][1]), int(label_list_split[1][1]), int(label_list_split[2][1]), int(label_list_split[3][1])]
197
+
198
+ # image = Image.open(img_path).convert('RGB')
199
+ # image = compress_image(img_path, 0.75)
200
+ # image = add_gaussian_noise(img_path, 20)
201
+ if self.transforms:
202
+ image = self.transforms(image)
203
+
204
+ return image, torch.FloatTensor(label_list), img_path
205
+ else:
206
+ raise ValueError(f"WRONG INPUT MODE: {self.mode}!")
207
+
208
+ def __len__(self):
209
+ return len(self.data)
FAITH/models/DCT.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from scipy.fftpack import dctn, idctn
4
+ from torch_dct import dct_2d, idct_2d
5
+
6
+
7
+ import pdb
8
+ import torch
9
+ from torch import nn
10
+ from PIL import Image
11
+ from torchvision import transforms
12
+
13
+
14
+ class DCT(nn.Module):
15
+ def __init__(self) -> None:
16
+ super().__init__()
17
+ self.conv = nn.Conv2d(1, 1, kernel_size=16, stride=16, padding=0, bias=False)
18
+ # self.pool = nn.AdaptiveAvgPool2d((32, 32))
19
+
20
+ def forward(self, images):
21
+ """ 输入维度: [B, C, H, W] """
22
+ # 灰度化(保持GPU计算)
23
+ images_gray = torch.mean(images, dim=1) # [B, H, W]
24
+
25
+ # 二维DCT变换
26
+ dct_coeff = dct_2d(images_gray, norm='ortho') # [B, H, W]
27
+
28
+ # 创建高通滤波器掩膜(保留右下四分之一)
29
+ B, H, W = dct_coeff.shape
30
+ mask = torch.zeros((H, W), device=images.device)
31
+ mask[H//2:, W//2:] = 1 # 右下区域
32
+ mask = mask.unsqueeze(0) # [1, H, W] 用于广播
33
+
34
+ # 应用高通滤波
35
+ dct_highpass = dct_coeff * mask # 广播乘法 [B, H, W]
36
+
37
+ # 逆DCT变换
38
+ img_highpass = idct_2d(dct_highpass, norm='ortho') # [B, H, W]
39
+ img_highpass = torch.abs(img_highpass) # 确保数值稳定性
40
+
41
+ # # masked_image = Image.fromarray(img_highpass) # .size: [512, 512]
42
+ # masked_image = transforms.ToPILImage()(img_highpass[0]) # .size: [512, 512]
43
+ # masked_image.save("./dct_test.jpg")
44
+
45
+ # 通过卷积层(保持通道维度)
46
+ coeffs = self.conv(img_highpass.unsqueeze(1)).flatten(1) # [B, 1024]
47
+
48
+ return coeffs
49
+
50
+
51
+ def forward_single_image(self, image):
52
+ image = np.array(image)
53
+ # 执行二维DCT变换
54
+ dct_coeff = dctn(image.astype(float), norm='ortho')
55
+
56
+ # 创建高频掩码(保留右下四分之一)
57
+ rows, cols = image.shape
58
+ mask = np.zeros((rows, cols))
59
+ mask[rows//2:, cols//2:] = 1
60
+
61
+ # 提取高频分量
62
+ high_freq_dct = dct_coeff * mask
63
+
64
+ # 逆DCT变换恢复高频图像
65
+ masked_image = idctn(high_freq_dct, norm='ortho')
66
+ masked_image = np.clip(masked_image, 0, 255).astype(np.uint8) * 10
67
+
68
+ masked_image = Image.fromarray(masked_image) # .size: [512, 512]
69
+ masked_image.save("./dct_test.jpg")
70
+
71
+ return masked_image
72
+
73
+
74
+
75
+ if __name__ == "__main__":
76
+ img_path = "../../../ultraedit/UltraEdit/sequential_deepfake_dataset/0/50.jpg"
77
+ image = Image.open(img_path).convert('RGB')
78
+
79
+ trans = transforms.Compose([
80
+ transforms.ColorJitter(brightness=[0.5, 1.3], contrast=[
81
+ 0.8, 1.5], saturation=[0.2, 1.5]), # 修改图像的亮度、对比度和饱和度
82
+ transforms.RandomHorizontalFlip(), # 按照概率p水平翻转图像
83
+ transforms.ToTensor(),
84
+ transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
85
+ ])
86
+
87
+ input_image = trans(image).unsqueeze(0)
88
+ print(input_image.shape)
89
+
90
+ # pdb.set_trace()
91
+ mask_generator = DCT()
92
+ output = mask_generator.forward(input_image)
FAITH/models/FFT.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pdb
2
+ import numpy as np
3
+ import torch
4
+ from torch import nn
5
+ from PIL import Image
6
+ from torchvision import transforms
7
+
8
+
9
+ class FFT(nn.Module):
10
+ def __init__(self) -> None:
11
+ super().__init__()
12
+ self.conv = nn.Conv2d(1, 1, kernel_size=16, stride=16, padding=0, bias=False)
13
+ # self.pool = nn.AdaptiveAvgPool2d((32, 32))
14
+
15
+
16
+ def forward(self, images):
17
+ # batch_size = images.shape[0]
18
+ # 灰度化 (保持GPU计算)
19
+ images_gray = torch.mean(images, dim=1) # [B, H, W]
20
+
21
+ # 快速傅里叶变换
22
+ fft_result = torch.fft.fft2(images_gray) # [B, H, W]
23
+
24
+ # 频谱中心化
25
+ fft_shifted = torch.fft.fftshift(fft_result, dim=(-2, -1))
26
+
27
+ # 创建高通滤波器掩膜(GPU上创建)
28
+ H, W = images_gray.shape[-2], images_gray.shape[-1]
29
+ radius = H // 8
30
+ mask = torch.ones((H, W), device=images.device)
31
+ center = H // 2
32
+ mask[center-radius:center+radius, center-radius:center+radius] = 0
33
+ mask = mask.unsqueeze(0) # [1, H, W] 用于广播
34
+
35
+ # 应用高通滤波
36
+ fft_shifted_highpass = fft_shifted * mask # 广播乘法
37
+
38
+ # 逆中心化
39
+ fft_ishift = torch.fft.ifftshift(fft_shifted_highpass, dim=(-2, -1))
40
+
41
+ # 逆傅里叶变换
42
+ img_complex = torch.fft.ifft2(fft_ishift)
43
+ img_highpass = torch.abs(img_complex) # [B, H, W]
44
+
45
+ # 通过卷积层
46
+ img_highpass = img_highpass.unsqueeze(1) # 添加通道维度 [B, 1, H, W]
47
+
48
+ # masked_image = Image.fromarray(np.array(img_highpass[0][0] * 100).astype(np.uint8)) # .size: [512, 512]
49
+ # masked_image.save("./test.jpg")
50
+
51
+ coeffs = self.conv(img_highpass).flatten(1) # [B, 1024]
52
+
53
+ # print(coeffs)
54
+ return coeffs
55
+
56
+
57
+ def forward_cpu(self, images):
58
+ batch_size = images.shape[0]
59
+ coeffs = torch.zeros(batch_size, 1024).cuda()
60
+ images = torch.mean(images, dim=1)
61
+
62
+ for i in range(batch_size):
63
+ img_array = np.array(images[i])
64
+ print(img_array.shape)
65
+ # 执行FFT并中心化
66
+ fft_result = np.fft.fft2(img_array)
67
+ fft_shifted = np.fft.fftshift(fft_result)
68
+
69
+ # 创建高通滤波器掩膜(保留高频,去除低频)
70
+ rows, cols = img_array.shape
71
+ center_row, center_col = rows // 2, cols // 2
72
+ radius = rows // 8 # 控制保留高频的范围,值越小保留的高频越多
73
+ mask = np.ones((rows, cols), np.uint8)
74
+ mask[center_row-radius:center_row+radius, center_col-radius:center_col+radius] = 0
75
+
76
+ # 应用掩膜,保留高频成分
77
+ fft_shifted_highpass = fft_shifted * mask
78
+
79
+ fft_ishift = np.fft.ifftshift(fft_shifted_highpass)
80
+ img_highpass = np.abs(np.fft.ifft2(fft_ishift)) * 100
81
+
82
+ masked_image = Image.fromarray(img_highpass.astype(np.uint8)) # .size: [512, 512]
83
+ masked_image.save("./test.jpg")
84
+ coeffs[i] = self.conv(torch.from_numpy(img_highpass).float().unsqueeze(0).unsqueeze(0).cuda()).flatten(0)
85
+
86
+ return coeffs
87
+
88
+
89
+ def forward2(self, image):
90
+ # batch_size = images.shape[0]
91
+ coeffs = torch.zeros(1, 1024).cuda()
92
+
93
+ # for i in range(batch_size):
94
+ if 1:
95
+ image_array = np.array(image).astype(np.complex64) # .shape: [512, 512, 3]
96
+ freq_image = np.fft.fftn(image_array, axes=(0, 1))
97
+
98
+ height, width = image_array.shape
99
+
100
+ mask = self._create_balanced_mask(height, width) # .shape: [512, 512, 3]
101
+ self.masked_freq_image = freq_image * mask
102
+ masked_image_array = np.fft.ifftn(self.masked_freq_image, axes=(0, 1)).real # .shape: [512, 512, 3]
103
+ masked_image = Image.fromarray(masked_image_array.astype(np.uint8))
104
+ # pdb.set_trace()
105
+ masked_image.save("./test.jpg")
106
+
107
+ # coeffs[i] = self.pool(self.conv(masked_image)).flatten(0)
108
+
109
+ return coeffs
110
+
111
+
112
+ def _create_balanced_mask(self, height, width):
113
+ mask = np.zeros((height, width), dtype=np.complex64)
114
+
115
+ # Determine the region of the frequency domain to mask
116
+ y_start, y_end = 3 * height // 4, height
117
+ x_start, x_end = 3 * width // 4, width
118
+
119
+ # num_frequencies = int(np.ceil((y_end - y_start) * (x_end - x_start) * self.ratio))
120
+ mask_frequencies_indices = np.random.permutation((y_end - y_start) * (x_end - x_start))
121
+ y_indices = mask_frequencies_indices // (x_end - x_start) + y_start
122
+ x_indices = mask_frequencies_indices % (x_end - x_start) + x_start
123
+
124
+ mask[y_indices, x_indices] = 1
125
+
126
+ return mask
127
+
128
+
129
+ class FrequencyMaskGenerator(nn.Module):
130
+ def __init__(self, ratio: float = 1, band: str = 'high') -> None:
131
+ # self.ratio = ratio
132
+ self.band = band # 'low', 'mid', 'high', 'all'
133
+
134
+ def transform(self, image: Image.Image) -> Image.Image:
135
+ image_array = np.array(image).astype(np.complex64) # .shape: [512, 512, 3]
136
+ freq_image = np.fft.fftn(image_array, axes=(0, 1))
137
+
138
+ height, width, _ = image_array.shape
139
+
140
+ mask = self._create_balanced_mask(height, width) # .shape: [512, 512, 3]
141
+ self.masked_freq_image = freq_image * mask
142
+ masked_image_array = np.fft.ifftn(self.masked_freq_image, axes=(0, 1)).real
143
+ masked_image = Image.fromarray(masked_image_array.astype(np.uint8))
144
+ return masked_image
145
+
146
+ def _create_balanced_mask(self, height, width):
147
+ mask = np.zeros((height, width, 3), dtype=np.complex64)
148
+
149
+ # Determine the region of the frequency domain to mask
150
+ if self.band == 'low':
151
+ y_start, y_end = 0, height // 4
152
+ x_start, x_end = 0, width // 4
153
+ elif self.band == 'mid':
154
+ y_start, y_end = height // 4, 3 * height // 4
155
+ x_start, x_end = width // 4, 3 * width // 4
156
+ elif self.band == 'high':
157
+ y_start, y_end = 3 * height // 4, height
158
+ x_start, x_end = 3 * width // 4, width
159
+ elif self.band == 'all':
160
+ y_start, y_end = 0, height
161
+ x_start, x_end = 0, width
162
+ else:
163
+ raise ValueError(f"Invalid band: {self.band}")
164
+
165
+ # num_frequencies = int(np.ceil((y_end - y_start) * (x_end - x_start) * self.ratio))
166
+ mask_frequencies_indices = np.random.permutation((y_end - y_start) * (x_end - x_start))
167
+ y_indices = mask_frequencies_indices // (x_end - x_start) + y_start
168
+ x_indices = mask_frequencies_indices % (x_end - x_start) + x_start
169
+
170
+ pdb.set_trace()
171
+
172
+ mask[y_indices, x_indices, :] = 1
173
+ return mask
174
+
175
+
176
+ if __name__ == "__main__":
177
+ img_path = "../../../ultraedit/UltraEdit/sequential_deepfake_dataset/0/50.jpg"
178
+ image = Image.open(img_path).convert('RGB')
179
+
180
+ transforms = transforms.Compose([
181
+ transforms.ColorJitter(brightness=[0.5, 1.3], contrast=[
182
+ 0.8, 1.5], saturation=[0.2, 1.5]), # 修改图像的亮度、对比度和饱和度
183
+ transforms.RandomHorizontalFlip(), # 按照概率p水平翻转图像
184
+ transforms.ToTensor(),
185
+ transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
186
+ ])
187
+
188
+ input_images = transforms(image).unsqueeze(0)
189
+ print(input_images.shape)
190
+
191
+ # pdb.set_trace()
192
+ mask_generator = FFT()
193
+ after_image = mask_generator.forward(input_images)
FAITH/models/FrozenCLIPTextEncoder.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pdb
2
+ import torch
3
+ from transformers import CLIPTokenizer, CLIPTextModel
4
+ import torch.nn as nn
5
+
6
+
7
+ class AbstractEncoder(nn.Module):
8
+ def __init__(self):
9
+ super().__init__()
10
+
11
+ def encode(self, *args, **kwargs):
12
+ raise NotImplementedError
13
+
14
+
15
+ ATTRIBUTE_MAPPING = {
16
+ 1: 'eye',
17
+ 2: 'lip',
18
+ 3: 'hair',
19
+ 4: 'glasses',
20
+ 5: 'hat',
21
+ 6: 'eyebrow'
22
+ }
23
+
24
+ ORDER_MAPPING = {
25
+ 1: 'first',
26
+ 2: 'second',
27
+ 3: 'third',
28
+ 4: 'last'
29
+ }
30
+
31
+
32
+ class FrozenCLIPEmbedder(AbstractEncoder):
33
+ """Uses the CLIP transformer encoder for text (from Hugging Face)"""
34
+ def __init__(self, version="openai/clip-vit-large-patch14", device="cuda", max_length=16):
35
+ super().__init__()
36
+ self.tokenizer = CLIPTokenizer.from_pretrained(version)
37
+ self.transformer = CLIPTextModel.from_pretrained(version)
38
+ self.device = device
39
+ self.max_length = max_length
40
+ self.freeze()
41
+
42
+ def freeze(self):
43
+ self.transformer = self.transformer.eval()
44
+ for param in self.parameters():
45
+ param.requires_grad = False
46
+
47
+ def forward(self, text):
48
+ assert torch.is_tensor(text)
49
+ input_shape = text.shape # .shape: [bs, 5]
50
+ # text = self.label_mapping(text) # len(text): bs * 5
51
+ batch_encoding = self.tokenizer(self.label_mapping(text), truncation=False, return_length=True,
52
+ return_overflowing_tokens=False, padding=True, return_tensors="pt")
53
+ tokens = batch_encoding["input_ids"].to(self.device)
54
+ # outputs = self.transformer(input_ids=tokens).pooler_output
55
+ outputs = self.transformer(input_ids=tokens).last_hidden_state[:, 1, :] # .shape: [bs * 5, 768]
56
+
57
+ # pdb.set_trace()
58
+ # outputs = torch.sum(outputs, dim=1)
59
+ # PAD 置零
60
+ indices = (text.contiguous().view(-1) == 8).nonzero(as_tuple=True)[0]
61
+ outputs[indices] = 0
62
+
63
+ outputs = outputs.contiguous().view(input_shape[0], input_shape[1], -1)
64
+ return outputs
65
+ # outputs = self.transformer(input_ids=tokens)
66
+
67
+ # z = outputs.last_hidden_state # .shape: [bs, max_length, 768]
68
+ # return z
69
+
70
+ def label_mapping(self, batch_sequence):
71
+ max_sequence_length = batch_sequence.shape[1]
72
+ # pdb.set_trace()
73
+
74
+ batch_sequence = batch_sequence.contiguous().view(-1).tolist() # .shape: [bs * 5]
75
+
76
+ sentences = []
77
+ for i, attribute in enumerate(batch_sequence):
78
+ # pdb.set_trace()
79
+ if attribute == 0:
80
+ sentence = "START"
81
+ elif attribute == 7:
82
+ sentence = "END"
83
+ elif attribute == 8: # TEST sequence : [SOS, PAD, PAD, PAD]
84
+ sentence = "PAD" # [bos, pad, pad] [40906, 40907]
85
+ else:
86
+ if i < len(batch_sequence) - 1 and batch_sequence[i + 1] == 8:
87
+ order = 'last'
88
+ else:
89
+ order = ORDER_MAPPING[i % max_sequence_length]
90
+ # sentence = f"The {ATTRIBUTE_MAPPING[attribute]} is edited {order}"
91
+ sentence = f"{ATTRIBUTE_MAPPING[attribute]} {order}"
92
+ sentences.append(sentence)
93
+
94
+ return sentences
95
+
96
+
97
+ def encode(self, text):
98
+ return self(text)
99
+
100
+
101
+
102
+ if __name__ == "__main__":
103
+ model = FrozenCLIPEmbedder().cuda()
104
+ model(torch.tensor([[0, 1, 2, 3, 4], [0, 3, 2, 8, 8], [0, 1, 5, 6, 8]]).cuda())
FAITH/models/SeqFakeFormer.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ import torch.nn.functional as F
4
+
5
+ from tools.utils import NestedTensor, nested_tensor_from_tensor_list
6
+ from .backbone import build_backbone
7
+ from .transformer_SECA import build_transformer
8
+ # import pdb
9
+ # from PIL import Image
10
+ # import requests
11
+
12
+ class SeqFakeFormer(nn.Module):
13
+ def __init__(self, backbone, transformer, hidden_dim, vocab_size, imgsize):
14
+ super().__init__()
15
+ self.backbone = backbone
16
+ self.imgsize = imgsize
17
+ self.input_proj = nn.Conv2d(
18
+ backbone.num_channels, hidden_dim, kernel_size=1)
19
+ self.transformer = transformer
20
+ self.mlp = MLP(hidden_dim, 512, vocab_size, 3) # FFN
21
+
22
+ def forward(self, samples, target, target_mask, img_path = None):
23
+ """
24
+ samples.shape: [bs, 3, img_size, img_size]
25
+ target.shape: [bs, max_position_embeddings]
26
+ target_mask.shape: [bs, max_position_embeddings]
27
+ """
28
+ # pdb.set_trace()
29
+ if not isinstance(samples, NestedTensor):
30
+ samples = nested_tensor_from_tensor_list(self.imgsize, samples)
31
+
32
+ features, pos = self.backbone(samples) # CNN (Resnet-50)
33
+
34
+ # src.shape: [bs, num_channels, 32, 32]; mask.shape: [bs, 32, 32]
35
+ src, mask = features[-1].decompose() # Resnet-50所指定的最后一层的feature map和mask
36
+ assert mask is not None
37
+
38
+ # height and width
39
+ h_w = torch.tensor([self.imgsize, self.imgsize]).repeat(src.shape[0], 1).to(src.device) # h_w.shape: [bs, 2]
40
+ h_w = h_w.unsqueeze(0) # h_w.shape: [1, bs, 2]
41
+
42
+ hs = self.transformer(self.input_proj(src), mask,
43
+ pos[-1], target, target_mask, h_w, samples.tensors, img_path) # hs.shape: [max_position_embeddings, bs, hidden_dim]
44
+
45
+ out = self.mlp(hs.permute(1, 0, 2)) # out.shape: [bs, max_position_embeddings, vocab_size]
46
+ # print(out)
47
+ return out
48
+
49
+
50
+ class MLP(nn.Module):
51
+ """ Very simple multi-layer perceptron (also called FFN)"""
52
+
53
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
54
+ super().__init__()
55
+ self.num_layers = num_layers
56
+ h = [hidden_dim] * (num_layers - 1)
57
+ # input_dim -> hidden_dim -> hidden_dim -> output_dim
58
+ self.layers = nn.ModuleList(nn.Linear(n, k)
59
+ for n, k in zip([input_dim] + h, h + [output_dim]))
60
+
61
+ def forward(self, x):
62
+ for i, layer in enumerate(self.layers):
63
+ x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
64
+ return x
65
+
66
+
67
+ def build_model(config):
68
+ backbone = build_backbone(config)
69
+ transformer = build_transformer(config)
70
+
71
+ model = SeqFakeFormer(backbone, transformer, config.hidden_dim, config.vocab_size, config.imgsize)
72
+
73
+ return model
FAITH/models/__init__.py ADDED
File without changes
FAITH/models/__pycache__/DCT.cpython-36.pyc ADDED
Binary file (2.37 kB). View file
 
FAITH/models/__pycache__/FFT.cpython-36.pyc ADDED
Binary file (5.08 kB). View file
 
FAITH/models/__pycache__/FrozenCLIPTextEncoder.cpython-36.pyc ADDED
Binary file (3.18 kB). View file
 
FAITH/models/__pycache__/FrozenCLIPTextEncoder.cpython-39.pyc ADDED
Binary file (3.23 kB). View file
 
FAITH/models/__pycache__/SeqFakeFormer.cpython-36.pyc ADDED
Binary file (2.76 kB). View file
 
FAITH/models/__pycache__/SeqFakeFormer.cpython-39.pyc ADDED
Binary file (2.79 kB). View file
 
FAITH/models/__pycache__/__init__.cpython-36.pyc ADDED
Binary file (136 Bytes). View file
 
FAITH/models/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (144 Bytes). View file
 
FAITH/models/__pycache__/attention_layer.cpython-36.pyc ADDED
Binary file (13.5 kB). View file
 
FAITH/models/__pycache__/attention_layer.cpython-39.pyc ADDED
Binary file (13.5 kB). View file
 
FAITH/models/__pycache__/backbone.cpython-36.pyc ADDED
Binary file (4.73 kB). View file
 
FAITH/models/__pycache__/backbone.cpython-39.pyc ADDED
Binary file (4.72 kB). View file
 
FAITH/models/__pycache__/configuration.cpython-36.pyc ADDED
Binary file (1.7 kB). View file
 
FAITH/models/__pycache__/configuration.cpython-39.pyc ADDED
Binary file (1.74 kB). View file
 
FAITH/models/__pycache__/position_encoding.cpython-36.pyc ADDED
Binary file (3.46 kB). View file
 
FAITH/models/__pycache__/position_encoding.cpython-39.pyc ADDED
Binary file (3.47 kB). View file
 
FAITH/models/__pycache__/transformer_SECA.cpython-36.pyc ADDED
Binary file (15.1 kB). View file
 
FAITH/models/__pycache__/transformer_SECA.cpython-39.pyc ADDED
Binary file (15.2 kB). View file
 
FAITH/models/attention_layer.py ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pdb
2
+ import cv2
3
+ import numpy as np
4
+ import torch
5
+ from torch.nn.functional import linear, pad
6
+ from torch import Tensor
7
+ from torch.nn import MultiheadAttention
8
+
9
+ from typing import Optional, Tuple, List
10
+ import warnings
11
+ import torch.nn.functional as F
12
+ import torchvision
13
+
14
+ import torch
15
+
16
+ def scale_to_target_range(source_tensor, target_tensor):
17
+ """
18
+ 将 source_tensor 的数据放缩到 target_tensor 的均值和方差范围
19
+ :param source_tensor: 需要放缩的 Tensor
20
+ :param target_tensor: 目标 Tensor, 提供均值和方差
21
+ :return: 放缩后的 Tensor
22
+ """
23
+ # 计算目标 Tensor 的均值和标准差
24
+ # pdb.set_trace()
25
+ target_mean = target_tensor.mean() / 5
26
+ target_std = target_tensor.std() / 5
27
+
28
+ # 计算源 Tensor 的均值和标准差
29
+ source_mean = source_tensor.mean()
30
+ source_std = source_tensor.std()
31
+
32
+ # 对源 Tensor 进行标准化(使其均值为 0,方差为 1)
33
+ source_normalized = (source_tensor - source_mean) / source_std
34
+
35
+ # 将标准化后的源 Tensor 放缩到目标 Tensor 的均值和方差
36
+ scaled_tensor = source_normalized * target_std + target_mean
37
+
38
+ return scaled_tensor
39
+
40
+
41
+
42
+ def multi_head_attention_forward(
43
+ query: Tensor,
44
+ key: Tensor,
45
+ value: Tensor,
46
+ embed_dim_to_check: int,
47
+ num_heads: int,
48
+ in_proj_weight: Tensor,
49
+ in_proj_bias: Tensor,
50
+ bias_k: Optional[Tensor],
51
+ bias_v: Optional[Tensor],
52
+ add_zero_attn: bool,
53
+ dropout_p: float,
54
+ out_proj_weight: Tensor,
55
+ out_proj_bias: Tensor,
56
+ training: bool = True,
57
+ key_padding_mask: Optional[Tensor] = None,
58
+ need_weights: bool = True,
59
+ attn_mask: Optional[Tensor] = None,
60
+ use_separate_proj_weight: bool = False,
61
+ q_proj_weight: Optional[Tensor] = None,
62
+ k_proj_weight: Optional[Tensor] = None,
63
+ v_proj_weight: Optional[Tensor] = None,
64
+ static_k: Optional[Tensor] = None,
65
+ static_v: Optional[Tensor] = None,
66
+ gaussian: Optional[Tensor] = None,
67
+ idx = -1,
68
+ images = None,
69
+ img_path = None
70
+ ) -> Tuple[Tensor, Optional[Tensor]]:
71
+ r"""
72
+ Args:
73
+ query, key, value: map a query and a set of key-value pairs to an output.
74
+ See "Attention Is All You Need" for more details.
75
+ embed_dim_to_check: total dimension of the model.
76
+ num_heads: parallel attention heads.
77
+ in_proj_weight, in_proj_bias: input projection weight and bias.
78
+ bias_k, bias_v: bias of the key and value sequences to be added at dim=0.
79
+ add_zero_attn: add a new batch of zeros to the key and
80
+ value sequences at dim=1.
81
+ dropout_p: probability of an element to be zeroed.
82
+ out_proj_weight, out_proj_bias: the output projection weight and bias.
83
+ training: apply dropout if is ``True``.
84
+ key_padding_mask: if provided, specified padding elements in the key will
85
+ be ignored by the attention. This is an binary mask. When the value is True,
86
+ the corresponding value on the attention layer will be filled with -inf.
87
+ need_weights: output attn_output_weights.
88
+ attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all
89
+ the batches while a 3D mask allows to specify a different mask for the entries of each batch.
90
+ use_separate_proj_weight: the function accept the proj. weights for query, key,
91
+ and value in different forms. If false, in_proj_weight will be used, which is
92
+ a combination of q_proj_weight, k_proj_weight, v_proj_weight.
93
+ q_proj_weight, k_proj_weight, v_proj_weight: input projection weight and bias.
94
+ static_k, static_v: static key and value used for attention operators.
95
+ gaussian: the generated Gaussian-like weight map
96
+ Shape:
97
+ Inputs:
98
+ - query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is
99
+ the embedding dimension.
100
+ - key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is
101
+ the embedding dimension.
102
+ - value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is
103
+ the embedding dimension.
104
+ - key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length.
105
+ If a ByteTensor is provided, the non-zero positions will be ignored while the zero positions
106
+ will be unchanged. If a BoolTensor is provided, the positions with the
107
+ value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.
108
+ - attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length.
109
+ 3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length,
110
+ S is the source sequence length. attn_mask ensures that position i is allowed to attend the unmasked
111
+ positions. If a ByteTensor is provided, the non-zero positions are not allowed to attend
112
+ while the zero positions will be unchanged. If a BoolTensor is provided, positions with ``True``
113
+ are not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
114
+ is provided, it will be added to the attention weight.
115
+ - static_k: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length,
116
+ N is the batch size, E is the embedding dimension. E/num_heads is the head dimension.
117
+ - static_v: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length,
118
+ N is the batch size, E is the embedding dimension. E/num_heads is the head dimension.
119
+ Outputs:
120
+ - attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size,
121
+ E is the embedding dimension.
122
+ - attn_output_weights: :math:`(N, L, S)` where N is the batch size,
123
+ L is the target sequence length, S is the source sequence length.
124
+ """
125
+ '''
126
+ query.shape: [5, bs, hidden_dim]
127
+ key.shape, value.shape: [1024, bs, hidden_dim]
128
+ embed_dim_to_check: hidden_dim
129
+ '''
130
+ tgt_len, bsz, embed_dim = query.size() # 5, bs, hidden_dim
131
+ assert embed_dim == embed_dim_to_check
132
+ # allow MHA to have different sizes for the feature dimension
133
+ assert key.size(0) == value.size(0) and key.size(1) == value.size(1)
134
+
135
+ head_dim = embed_dim // num_heads
136
+ assert head_dim * num_heads == embed_dim, "embed_dim must be divisible by num_heads"
137
+ scaling = float(head_dim) ** -0.5
138
+
139
+ if not use_separate_proj_weight:
140
+ if torch.equal(query, key) and torch.equal(key, value):
141
+ # self-attention
142
+ q, k, v = linear(query, in_proj_weight, in_proj_bias).chunk(3, dim=-1)
143
+
144
+ elif torch.equal(key, value):
145
+ # encoder-decoder attention
146
+ # This is inline in_proj function with in_proj_weight and in_proj_bias
147
+ _b = in_proj_bias
148
+ _start = 0
149
+ _end = embed_dim
150
+ _w = in_proj_weight[_start:_end, :]
151
+ if _b is not None:
152
+ _b = _b[_start:_end]
153
+ q = linear(query, _w, _b)
154
+
155
+ if key is None:
156
+ assert value is None
157
+ k = None
158
+ v = None
159
+ else:
160
+ # This is inline in_proj function with in_proj_weight and in_proj_bias
161
+ _b = in_proj_bias
162
+ _start = embed_dim
163
+ _end = None
164
+ _w = in_proj_weight[_start:, :]
165
+ if _b is not None:
166
+ _b = _b[_start:]
167
+ k, v = linear(key, _w, _b).chunk(2, dim=-1)
168
+ else:
169
+ # This is inline in_proj function with in_proj_weight and in_proj_bias
170
+ _b = in_proj_bias # Parameter(torch.empty(3 * embed_dim))
171
+ _start = 0
172
+ _end = embed_dim
173
+ _w = in_proj_weight[_start:_end, :]
174
+ if _b is not None:
175
+ _b = _b[_start:_end] # Parameter(torch.empty(embed_dim))
176
+ q = linear(query, _w, _b) # .shape: [5, bs, hidden_dim]
177
+
178
+ # This is inline in_proj function with in_proj_weight and in_proj_bias
179
+ _b = in_proj_bias
180
+ _start = embed_dim
181
+ _end = embed_dim * 2
182
+ _w = in_proj_weight[_start:_end, :]
183
+ if _b is not None:
184
+ _b = _b[_start:_end]
185
+ k = linear(key, _w, _b) # [1024, bs, hidden_dim]
186
+
187
+ # This is inline in_proj function with in_proj_weight and in_proj_bias
188
+ _b = in_proj_bias
189
+ _start = embed_dim * 2
190
+ _end = None
191
+ _w = in_proj_weight[_start:, :]
192
+ if _b is not None:
193
+ _b = _b[_start:]
194
+ v = linear(value, _w, _b) # [1024, bs, hidden_dim]
195
+ else:
196
+ q_proj_weight_non_opt = torch.jit._unwrap_optional(q_proj_weight)
197
+ len1, len2 = q_proj_weight_non_opt.size()
198
+ assert len1 == embed_dim and len2 == query.size(-1)
199
+
200
+ k_proj_weight_non_opt = torch.jit._unwrap_optional(k_proj_weight)
201
+ len1, len2 = k_proj_weight_non_opt.size()
202
+ assert len1 == embed_dim and len2 == key.size(-1)
203
+
204
+ v_proj_weight_non_opt = torch.jit._unwrap_optional(v_proj_weight)
205
+ len1, len2 = v_proj_weight_non_opt.size()
206
+ assert len1 == embed_dim and len2 == value.size(-1)
207
+
208
+ if in_proj_bias is not None:
209
+ q = linear(query, q_proj_weight_non_opt, in_proj_bias[0:embed_dim])
210
+ k = linear(key, k_proj_weight_non_opt, in_proj_bias[embed_dim:(embed_dim * 2)])
211
+ v = linear(value, v_proj_weight_non_opt, in_proj_bias[(embed_dim * 2):])
212
+ else:
213
+ q = linear(query, q_proj_weight_non_opt, in_proj_bias)
214
+ k = linear(key, k_proj_weight_non_opt, in_proj_bias)
215
+ v = linear(value, v_proj_weight_non_opt, in_proj_bias)
216
+ q = q * scaling
217
+
218
+ if attn_mask is not None:
219
+ assert attn_mask.dtype == torch.float32 or attn_mask.dtype == torch.float64 or \
220
+ attn_mask.dtype == torch.float16 or attn_mask.dtype == torch.uint8 or attn_mask.dtype == torch.bool, \
221
+ 'Only float, byte, and bool types are supported for attn_mask, not {}'.format(attn_mask.dtype)
222
+ if attn_mask.dtype == torch.uint8:
223
+ warnings.warn("Byte tensor for attn_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.")
224
+ attn_mask = attn_mask.to(torch.bool)
225
+
226
+ if attn_mask.dim() == 2:
227
+ attn_mask = attn_mask.unsqueeze(0)
228
+ if list(attn_mask.size()) != [1, query.size(0), key.size(0)]:
229
+ raise RuntimeError('The size of the 2D attn_mask is not correct.')
230
+ elif attn_mask.dim() == 3:
231
+ if list(attn_mask.size()) != [bsz * num_heads, query.size(0), key.size(0)]:
232
+ raise RuntimeError('The size of the 3D attn_mask is not correct.')
233
+ else:
234
+ raise RuntimeError("attn_mask's dimension {} is not supported".format(attn_mask.dim()))
235
+ # attn_mask's dim is 3 now.
236
+
237
+ # convert ByteTensor key_padding_mask to bool
238
+ if key_padding_mask is not None and key_padding_mask.dtype == torch.uint8:
239
+ warnings.warn("Byte tensor for key_padding_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.")
240
+ key_padding_mask = key_padding_mask.to(torch.bool)
241
+
242
+ if bias_k is not None and bias_v is not None:
243
+ if static_k is None and static_v is None:
244
+ k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
245
+ v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
246
+ if attn_mask is not None:
247
+ attn_mask = pad(attn_mask, (0, 1))
248
+ if key_padding_mask is not None:
249
+ key_padding_mask = pad(key_padding_mask, (0, 1))
250
+ else:
251
+ assert static_k is None, "bias cannot be added to static key."
252
+ assert static_v is None, "bias cannot be added to static value."
253
+ else:
254
+ assert bias_k is None
255
+ assert bias_v is None
256
+
257
+ q = q.contiguous().view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1) # .shape: [bs * nhead, tgt_len, head_dim]
258
+ if k is not None:
259
+ k = k.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) # .shape: [bs * nhead, 1024, head_dim]
260
+ if v is not None:
261
+ v = v.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) # .shape: [bs * nhead, 1024, head_dim]
262
+
263
+ if static_k is not None:
264
+ assert static_k.size(0) == bsz * num_heads
265
+ assert static_k.size(2) == head_dim
266
+ k = static_k
267
+
268
+ if static_v is not None:
269
+ assert static_v.size(0) == bsz * num_heads
270
+ assert static_v.size(2) == head_dim
271
+ v = static_v
272
+
273
+ src_len = k.size(1)
274
+
275
+ if key_padding_mask is not None: # .shape: [bs, 1024]
276
+ assert key_padding_mask.size(0) == bsz
277
+ assert key_padding_mask.size(1) == src_len
278
+
279
+ if add_zero_attn:
280
+ src_len += 1
281
+ k = torch.cat([k, torch.zeros((k.size(0), 1) + k.size()[2:], dtype=k.dtype, device=k.device)], dim=1)
282
+ v = torch.cat([v, torch.zeros((v.size(0), 1) + v.size()[2:], dtype=v.dtype, device=v.device)], dim=1)
283
+ if attn_mask is not None:
284
+ attn_mask = pad(attn_mask, (0, 1))
285
+ if key_padding_mask is not None:
286
+ key_padding_mask = pad(key_padding_mask, (0, 1))
287
+ naive = True
288
+ if naive:
289
+ attn_output_weights = torch.bmm(q, k.transpose(1, 2)) # .shape: [bs * nhead, tgt_len, 1024]
290
+ assert list(attn_output_weights.size()) == [bsz * num_heads, tgt_len, src_len]
291
+
292
+ if attn_mask is not None:
293
+ if attn_mask.dtype == torch.bool:
294
+ attn_output_weights.masked_fill_(attn_mask, float('-inf'))
295
+ else:
296
+ attn_output_weights += attn_mask
297
+
298
+ if key_padding_mask is not None:
299
+ attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
300
+ attn_output_weights = attn_output_weights.masked_fill(
301
+ key_padding_mask.unsqueeze(1).unsqueeze(2), float('-inf'),)
302
+ attn_output_weights = attn_output_weights.view(bsz * num_heads, tgt_len, src_len)
303
+
304
+ # gaussian[0].shape: [5, 1024, bs * nhead]
305
+
306
+ delta = gaussian[0].permute(2, 0, 1)
307
+ delta = scale_to_target_range(delta, attn_output_weights)
308
+ # pdb.set_trace()
309
+
310
+ attn_output_weights = attn_output_weights + delta
311
+ # attention_map = attn_output_weights[0, 2, :].view(32, 32)
312
+
313
+ # attention_map = (attention_map - attention_map.min()) / (attention_map.max() - attention_map.min())
314
+ # attention_map = F.interpolate(attention_map.unsqueeze(0).unsqueeze(0), size=[512, 512],mode='bilinear').detach().cpu()
315
+ # attention_map = np.uint8(255 * attention_map)[0][0] # .shape: [512, 512]
316
+
317
+ # normed_mask = cv2.applyColorMap(attention_map, cv2.COLORMAP_JET) # .shape: [512, 512, 3]
318
+
319
+ # # print(image_path[bs], input_caps[bs].detach().cpu(), caps[bs, 1:])
320
+ # a = cv2.resize(cv2.imread(img_path[0]), (512, 512)) # .shape: [512, 512, 3]
321
+ # normed_mask = cv2.addWeighted(a, 0.7, normed_mask, 0.5, 0)
322
+ # cv2.imwrite("./attn_maps/test.png", normed_mask)
323
+
324
+ attn_output_weights = torch.nn.functional.softmax(attn_output_weights, dim=-1)
325
+ attn_output_weights = torch.nn.functional.dropout(attn_output_weights, p=dropout_p,
326
+ training=training)
327
+
328
+ attn_output = torch.bmm(attn_output_weights, v)
329
+ assert list(attn_output.size()) == [bsz * num_heads, tgt_len, head_dim]
330
+
331
+ attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
332
+ attn_output = linear(attn_output, out_proj_weight, out_proj_bias) # .shape: [tgt_len, bs, hidden_dim]
333
+
334
+ return attn_output, attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
335
+
336
+
337
+ class GaussianMultiheadAttention(MultiheadAttention):
338
+ def __init__(self, embed_dim, num_heads, **kwargs):
339
+ super(GaussianMultiheadAttention, self).__init__(embed_dim, num_heads, **kwargs)
340
+ self.gaussian = True
341
+
342
+ def forward(self, query, key, value, key_padding_mask=None,
343
+ need_weights=False, attn_mask=None, gaussian=None, idx = -1, images=None, img_path = None):
344
+ # type: (Tensor, Tensor, Tensor, Optional[Tensor], bool, Optional[Tensor], Optional[Tensor]) -> Tuple[Tensor, Optional[Tensor]]
345
+ r"""
346
+ Args:
347
+ query, key, value: map a query and a set of key-value pairs to an output.
348
+ See "Attention Is All You Need" for more details.
349
+ key_padding_mask: if provided, specified padding elements in the key will
350
+ be ignored by the attention. When given a binary mask and a value is True,
351
+ the corresponding value on the attention layer will be ignored. When given
352
+ a byte mask and a value is non-zero, the corresponding value on the attention
353
+ layer will be ignored
354
+ need_weights: output attn_output_weights.
355
+ attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all
356
+ the batches while a 3D mask allows to specify a different mask for the entries of each batch.
357
+ gaussian: 2D gaussian attention map that focus attention to certain object queries' initial estimations
358
+ with handcrafted query spatial priors.
359
+
360
+ Shape:
361
+ - Inputs:
362
+ - query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is
363
+ the embedding dimension.
364
+ - key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is
365
+ the embedding dimension.
366
+ - value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is
367
+ the embedding dimension.
368
+ - key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length.
369
+ If a ByteTensor is provided, the non-zero positions will be ignored while the position
370
+ with the zero positions will be unchanged. If a BoolTensor is provided, the positions with the
371
+ value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.
372
+ - attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length.
373
+ 3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length,
374
+ S is the source sequence length. attn_mask ensure that position i is allowed to attend the unmasked
375
+ positions. If a ByteTensor is provided, the non-zero positions are not allowed to attend
376
+ while the zero positions will be unchanged. If a BoolTensor is provided, positions with ``True``
377
+ is not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
378
+ is provided, it will be added to the attention weight.
379
+ - gaussian: :math:`(L, S, nhead * batch_size)`, where nhead is the number of head in multi-head
380
+ attention module, L is the target sequence length, S is the source sequence length.
381
+
382
+ - Outputs:
383
+ - attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size,
384
+ E is the embedding dimension.
385
+ - attn_output_weights: :math:`(N, L, S)` where N is the batch size,
386
+ L is the target sequence length, S is the source sequence length.
387
+ """
388
+ if not self._qkv_same_embed_dim:
389
+ return multi_head_attention_forward(
390
+ query, key, value, self.embed_dim, self.num_heads,
391
+ self.in_proj_weight, self.in_proj_bias,
392
+ self.bias_k, self.bias_v, self.add_zero_attn,
393
+ self.dropout, self.out_proj.weight, self.out_proj.bias,
394
+ training=self.training,
395
+ key_padding_mask=key_padding_mask, need_weights=need_weights,
396
+ attn_mask=attn_mask, use_separate_proj_weight=True,
397
+ q_proj_weight=self.q_proj_weight, k_proj_weight=self.k_proj_weight,
398
+ v_proj_weight=self.v_proj_weight, gaussian=gaussian)
399
+ else: # here: self._qkv_same_embed_dim = True
400
+ return multi_head_attention_forward(
401
+ query, key, value, self.embed_dim, self.num_heads,
402
+ self.in_proj_weight, self.in_proj_bias,
403
+ self.bias_k, self.bias_v, self.add_zero_attn,
404
+ self.dropout, self.out_proj.weight, self.out_proj.bias,
405
+ training=self.training,
406
+ key_padding_mask=key_padding_mask, need_weights=need_weights,
407
+ attn_mask=attn_mask, gaussian=gaussian, idx = idx, images=images, img_path = img_path)
408
+
409
+
FAITH/models/backbone.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pdb
2
+ import torch
3
+ import torch.nn.functional as F
4
+ import torchvision
5
+ from torch import nn
6
+ from torchvision.models._utils import IntermediateLayerGetter
7
+ from typing import Dict, List
8
+
9
+ from tools.utils import NestedTensor, is_main_process
10
+ from .position_encoding import build_position_encoding
11
+
12
+
13
+ class FrozenBatchNorm2d(torch.nn.Module):
14
+ """
15
+ BatchNorm2d where the batch statistics and the affine parameters are fixed.
16
+ Copy-paste from torchvision.misc.ops with added eps before rqsrt,
17
+ without which any other models than torchvision.models.resnet[18,34,50,101]
18
+ produce nans.
19
+ """
20
+
21
+ def __init__(self, n):
22
+ super(FrozenBatchNorm2d, self).__init__()
23
+ self.register_buffer("weight", torch.ones(n))
24
+ self.register_buffer("bias", torch.zeros(n))
25
+ self.register_buffer("running_mean", torch.zeros(n))
26
+ self.register_buffer("running_var", torch.ones(n))
27
+
28
+ def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
29
+ missing_keys, unexpected_keys, error_msgs):
30
+ num_batches_tracked_key = prefix + 'num_batches_tracked'
31
+ if num_batches_tracked_key in state_dict:
32
+ del state_dict[num_batches_tracked_key]
33
+
34
+ super(FrozenBatchNorm2d, self)._load_from_state_dict(
35
+ state_dict, prefix, local_metadata, strict,
36
+ missing_keys, unexpected_keys, error_msgs)
37
+
38
+ def forward(self, x):
39
+ # move reshapes to the beginning
40
+ # to make it fuser-friendly
41
+ w = self.weight.reshape(1, -1, 1, 1)
42
+ b = self.bias.reshape(1, -1, 1, 1)
43
+ rv = self.running_var.reshape(1, -1, 1, 1)
44
+ rm = self.running_mean.reshape(1, -1, 1, 1)
45
+ eps = 1e-5
46
+ scale = w * (rv + eps).rsqrt()
47
+ bias = b - rm * scale
48
+ return x * scale + bias
49
+
50
+
51
+ class BackboneBase(nn.Module):
52
+ def __init__(self, backbone: nn.Module, train_backbone: bool, num_channels: int, return_interm_layers: bool):
53
+ super().__init__()
54
+ for name, parameter in backbone.named_parameters():
55
+ if not train_backbone or 'layer2' not in name and 'layer3' not in name and 'layer4' not in name:
56
+ parameter.requires_grad_(False)
57
+ if return_interm_layers:
58
+ return_layers = {"layer1": "0", "layer2": "1", "layer3": "2", "layer4": "3"}
59
+ else:
60
+ return_layers = {'layer4': "0"}
61
+ self.body = IntermediateLayerGetter(backbone, return_layers=return_layers) # 获取中间层的输出
62
+ self.num_channels = num_channels
63
+
64
+ def forward(self, tensor_list: NestedTensor):
65
+ # print(tensor_list.mask)
66
+ xs = self.body(tensor_list.tensors) # xs['0'].shape: [bs, 2048, 32, 32]
67
+ out: Dict[str, NestedTensor] = {}
68
+ for name, x in xs.items():
69
+ m = tensor_list.mask # m.shape: [bs, img_size, img_size] all False
70
+ assert m is not None
71
+ mask = F.interpolate(m[None].float(), size=x.shape[-2:]).to(torch.bool)[0] # [bs, 32, 32] all False
72
+ out[name] = NestedTensor(x, mask)
73
+ return out
74
+
75
+
76
+ class Backbone(BackboneBase):
77
+ """ResNet backbone with frozen BatchNorm."""
78
+ def __init__(self, name: str,
79
+ train_backbone: bool,
80
+ return_interm_layers: bool,
81
+ dilation: bool,
82
+ Frozen_BatchNorm2d: bool):
83
+ if Frozen_BatchNorm2d:
84
+ backbone = getattr(torchvision.models, name)(
85
+ replace_stride_with_dilation=[False, False, dilation],
86
+ pretrained=is_main_process(), norm_layer=FrozenBatchNorm2d)
87
+ else:
88
+ backbone = getattr(torchvision.models, name)(
89
+ replace_stride_with_dilation=[False, False, dilation],
90
+ pretrained=is_main_process(), norm_layer=nn.BatchNorm2d)
91
+ num_channels = 512 if name in ('resnet18', 'resnet34') else 2048
92
+ super().__init__(backbone, train_backbone, num_channels, return_interm_layers)
93
+
94
+
95
+ class Joiner(nn.Sequential):
96
+ def __init__(self, backbone, position_embedding):
97
+ super().__init__(backbone, position_embedding)
98
+
99
+ def forward(self, tensor_list: NestedTensor):
100
+ xs = self[0](tensor_list)
101
+ out: List[NestedTensor] = []
102
+ pos = []
103
+ for name, x in xs.items():
104
+ out.append(x)
105
+ # position encoding
106
+ pos.append(self[1](x).to(x.tensors.dtype)) # pos[0].shape: [bs, 512, 32, 32]
107
+
108
+ return out, pos
109
+
110
+
111
+ def build_backbone(config):
112
+
113
+ position_embedding = build_position_encoding(config)
114
+
115
+ train_backbone = config.lr_backbone > 0
116
+ return_interm_layers = False
117
+ backbone = Backbone(config.backbone, train_backbone, return_interm_layers, config.dilation, config.Frozen_BatchNorm2d)
118
+ model = Joiner(backbone, position_embedding)
119
+ model.num_channels = backbone.num_channels
120
+
121
+ return model
FAITH/models/configuration.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ class Config(object):
4
+ def __init__(self, config_file):
5
+ with open(config_file) as f:
6
+ cfgs = json.load(f)
7
+
8
+ # Learning Rates
9
+ self.lr_backbone = cfgs["optimizer"]["lr_backbone"]
10
+ self.lr = cfgs["optimizer"]["lr"]
11
+
12
+ # Epochs
13
+ self.epochs = cfgs["optimizer"]["epochs"]
14
+ self.warmup = cfgs["optimizer"]["warmup"]
15
+ self.warmup_epochs = cfgs["optimizer"]["warmup_epochs"]
16
+ self.lr_milestones = cfgs["optimizer"]["lr_milestones"]
17
+
18
+ self.start_epoch = cfgs["optimizer"]["start_epoch"]
19
+ self.weight_decay = cfgs["optimizer"]["weight_decay"]
20
+
21
+ # Backbone
22
+ # resnet34 resnet50
23
+ self.backbone = cfgs["backbone"]["network"]
24
+ if self.backbone == 'resnet50' or self.backbone == 'resnet101':
25
+ self.dilation = True
26
+ elif self.backbone == 'resnet34' or self.backbone == 'resnet18':
27
+ self.dilation = False
28
+ else:
29
+ raise ValueError(f"{self.backbone} is not a supported backbone!")
30
+
31
+ self.position_embedding = cfgs["backbone"]["position_embedding"] # sine learned
32
+ self.Frozen_BatchNorm2d = cfgs["backbone"]["Frozen_BatchNorm2d"]
33
+
34
+ # Basic
35
+ self.batch_size = cfgs["optimizer"]["batch_size"]
36
+ self.clip_max_norm = cfgs["optimizer"]["clip_max_norm"]
37
+
38
+ # Transformer
39
+ self.SOS_token_id = cfgs["transformer"]["SOS_token_id"]
40
+ self.EOS_token_id = cfgs["transformer"]["EOS_token_id"]
41
+ self.PAD_token_id = cfgs["transformer"]["PAD_token_id"]
42
+
43
+ self.smooth = cfgs["transformer"]["smooth"]
44
+ self.dynamic_scale = cfgs["transformer"]["dynamic_scale"]
45
+
46
+ self.max_position_embeddings = cfgs["transformer"]["max_position_embeddings"]
47
+ self.vocab_size = cfgs["transformer"]["vocab_size"]
48
+
49
+
50
+ self.layer_norm_eps = cfgs["transformer"]["layer_norm_eps"]
51
+ self.dropout = cfgs["transformer"]["dropout"]
52
+
53
+ self.hidden_dim = cfgs["transformer"]["hidden_dim"]
54
+ self.enc_layers = cfgs["transformer"]["enc_layers"]
55
+ self.dec_layers = cfgs["transformer"]["dec_layers"]
56
+ self.dim_feedforward = cfgs["transformer"]["dim_feedforward"]
57
+ self.nheads = cfgs["transformer"]["nheads"]
58
+ self.pre_norm = cfgs["transformer"]["pre_norm"]
59
+
60
+ # Dataset
61
+ self.imgsize = cfgs["dataset"]["imgsize"]
FAITH/models/dct_test.jpg ADDED

Git LFS Details

  • SHA256: 035d99b231aa36b77782a1f550418fdf33a293481bff0fdf0a992f40d87dcd76
  • Pointer size: 130 Bytes
  • Size of remote file: 10.5 kB
FAITH/models/position_encoding.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn
4
+
5
+ from tools.utils import NestedTensor
6
+
7
+
8
+ class PositionEmbeddingSine(nn.Module):
9
+ """
10
+ This is a more standard version of the position embedding, very similar to the one
11
+ used by the Attention is all you need paper, generalized to work on images.
12
+ """
13
+ def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None):
14
+ super().__init__()
15
+ self.num_pos_feats = num_pos_feats
16
+ self.temperature = temperature
17
+ self.normalize = normalize
18
+ if scale is not None and normalize is False:
19
+ raise ValueError("normalize should be True if scale is passed")
20
+ if scale is None:
21
+ scale = 2 * math.pi
22
+ self.scale = scale
23
+
24
+ def forward(self, tensor_list: NestedTensor):
25
+ x = tensor_list.tensors
26
+ mask = tensor_list.mask
27
+ assert mask is not None
28
+ not_mask = ~mask
29
+ y_embed = not_mask.cumsum(1, dtype=torch.float32)
30
+ x_embed = not_mask.cumsum(2, dtype=torch.float32)
31
+ if self.normalize:
32
+ eps = 1e-6
33
+ y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
34
+ x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale
35
+
36
+ dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
37
+ dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
38
+
39
+ pos_x = x_embed[:, :, :, None] / dim_t
40
+ pos_y = y_embed[:, :, :, None] / dim_t
41
+ pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
42
+ pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
43
+ pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
44
+ return pos
45
+
46
+
47
+ class PositionEmbeddingLearned(nn.Module):
48
+ """
49
+ Absolute pos embedding, learned.
50
+ """
51
+ def __init__(self, num_pos_feats=256):
52
+ super().__init__()
53
+ self.row_embed = nn.Embedding(50, num_pos_feats)
54
+ self.col_embed = nn.Embedding(50, num_pos_feats)
55
+ self.reset_parameters()
56
+
57
+ def reset_parameters(self):
58
+ nn.init.uniform_(self.row_embed.weight)
59
+ nn.init.uniform_(self.col_embed.weight)
60
+
61
+ def forward(self, tensor_list: NestedTensor):
62
+ x = tensor_list.tensors
63
+ h, w = x.shape[-2:]
64
+ i = torch.arange(w, device=x.device)
65
+ j = torch.arange(h, device=x.device)
66
+ x_emb = self.col_embed(i)
67
+ y_emb = self.row_embed(j)
68
+ pos = torch.cat([
69
+ x_emb.unsqueeze(0).repeat(h, 1, 1),
70
+ y_emb.unsqueeze(1).repeat(1, w, 1),
71
+ ], dim=-1).permute(2, 0, 1).unsqueeze(0).repeat(x.shape[0], 1, 1, 1)
72
+ return pos
73
+
74
+
75
+ def build_position_encoding(config):
76
+ N_steps = config.hidden_dim // 2
77
+ if config.position_embedding in ('v2', 'sine'):
78
+ # TODO find a better way of exposing other arguments
79
+ position_embedding = PositionEmbeddingSine(N_steps, normalize=True)
80
+ elif config.position_embedding in ('v3', 'learned'):
81
+ position_embedding = PositionEmbeddingLearned(N_steps)
82
+ else:
83
+ raise ValueError(f"not supported {config.position_embedding}")
84
+
85
+ return position_embedding
FAITH/models/test.jpg ADDED

Git LFS Details

  • SHA256: 6679b1ff42c8e6793eaa345373c28eca1489d1a4f1ef7f06c8e1d7952d6ec702
  • Pointer size: 130 Bytes
  • Size of remote file: 13.9 kB
FAITH/models/transformer_SECA.py ADDED
@@ -0,0 +1,630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ from typing import Optional, List
3
+
4
+ import cv2
5
+ import numpy as np
6
+ import torch
7
+ import torch.nn.functional as F
8
+ from torch import nn, Tensor
9
+ import pdb
10
+
11
+ # from .FrozenCLIPTextEncoder import FrozenCLIPEmbedder
12
+ from .attention_layer import GaussianMultiheadAttention
13
+ from pytorch_wavelets import DWTForward # (or import DWT, IDWT)
14
+ # from .FFT import FFT
15
+ # from .DCT import DCT
16
+
17
+ class Transformer(nn.Module):
18
+
19
+ def __init__(self, config, d_model=512, nhead=8, num_encoder_layers=6,
20
+ num_decoder_layers=6, dim_feedforward=2048, dropout=0.1,
21
+ activation="relu", normalize_before=False,
22
+ return_intermediate_dec=False, smooth=8, dynamic_scale=True):
23
+ super().__init__()
24
+
25
+ encoder_layer = TransformerEncoderLayer(d_model, nhead, dim_feedforward,
26
+ dropout, activation, normalize_before)
27
+ encoder_norm = nn.LayerNorm(d_model) if normalize_before else None
28
+ self.encoder = TransformerEncoder(encoder_layer, num_encoder_layers, encoder_norm) # Transformer Encooder
29
+
30
+ self.embeddings = DecoderEmbeddings(config)
31
+
32
+ decoder_layers = []
33
+ for layer_index in range(num_decoder_layers):
34
+ decoder_layer = TransformerDecoderLayer(dynamic_scale, smooth, layer_index,
35
+ d_model, nhead, dim_feedforward, dropout,
36
+ activation, normalize_before)
37
+ decoder_layers.append(decoder_layer)
38
+ decoder_norm = nn.LayerNorm(d_model)
39
+ self.decoder = TransformerDecoder(decoder_layers, num_decoder_layers, decoder_norm,
40
+ return_intermediate=return_intermediate_dec) # Transformer Decoder
41
+
42
+ self._reset_parameters()
43
+ # if dynamic_scale in ["type2", "type3", "type4"]:
44
+ # for layer_index in range(num_decoder_layers):
45
+ # nn.init.zeros_(self.decoder.layers[layer_index].point3.weight) # 用全0初始化权重
46
+ # with torch.no_grad():
47
+ # nn.init.ones_(self.decoder.layers[layer_index].point3.bias) # 用全1初始化偏差
48
+
49
+ # nn.init.normal_(self.embeddings.projection_layer.weight, mean=0.05, std=0.01)
50
+
51
+ self.d_model = d_model
52
+ self.nhead = nhead
53
+
54
+ def _reset_parameters(self):
55
+ for p in self.parameters():
56
+ if p.dim() > 1:
57
+ nn.init.xavier_uniform_(p) # 用均匀分布初始化参数
58
+
59
+ def forward(self, src, mask, pos_embed, tgt, tgt_mask, h_w, images, img_path = None):
60
+ # flatten NxCxHxW to HWxNxC
61
+ '''
62
+ src.shape: [bs, hidden_dim, 32, 32]
63
+ mask.shape: [bs, 32, 32]
64
+ pos_embed.shape: [bs, 512, 32, 32]
65
+ tgt.shape: [bs, 5]
66
+ tgt_mask.shape: [bs, 5]
67
+ h_w.shape: [1, bs, 2]
68
+ '''
69
+ bs, c, h, w = src.shape
70
+ grid_y, grid_x = torch.meshgrid(torch.arange(0, h), torch.arange(0, w)) # 返回一个h × w大小的网格,可用于生成坐标 # grid_y.shape: [32, 32], grid_x.shape: [32, 32]
71
+ grid = torch.stack((grid_x, grid_y), 2).float().to(src.device) # grid.shape: [32, 32, 2]
72
+ grid = grid.reshape(-1, 2).unsqueeze(1).repeat(1, bs * self.nhead, 1) # grid.shape: [1024, bs * self.nhead, 2]
73
+
74
+ src = src.flatten(2).permute(2, 0, 1) # src.shape: [1024, bs, hidden_dim]
75
+ pos_embed = pos_embed.flatten(2).permute(2, 0, 1) # pos_embed.shape: [1024, bs, 512]
76
+
77
+ tgt = self.embeddings(tgt).permute(1, 0, 2) # Tokenizer tgt.shape: [5, bs, hidden_dim]
78
+ query_embed = self.embeddings.position_embeddings.weight.unsqueeze(1) # query_embed.shape: [5, 1, hidden_dim]
79
+ query_embed = query_embed.repeat(1, bs, 1) # query_embed.shape: [5, bs, hidden_dim]
80
+
81
+ mask = mask.flatten(1) # mask.shape: [bs, 1024]
82
+
83
+ # original Transformer visual encoder
84
+ memory = self.encoder(src, src_key_padding_mask=mask, pos=pos_embed) # memory.shape: [1024, bs, hidden_dim]
85
+
86
+ hs = self.decoder(grid, h_w, tgt, memory, memory_key_padding_mask=mask, tgt_key_padding_mask=tgt_mask,
87
+ pos=pos_embed, query_pos=query_embed,
88
+ tgt_mask=generate_square_subsequent_mask(len(tgt)).to(tgt.device), images=images, img_path = img_path) # hs.shape: [max_position_embeddings, bs, hidden_dim]
89
+ # print(hs)
90
+ return hs
91
+
92
+
93
+ class TransformerEncoder(nn.Module):
94
+
95
+ def __init__(self, encoder_layer, num_layers, norm=None):
96
+ super().__init__()
97
+ self.layers = _get_clones(encoder_layer, num_layers)
98
+ self.num_layers = num_layers
99
+ self.norm = norm
100
+
101
+ def forward(self, src,
102
+ mask: Optional[Tensor] = None,
103
+ src_key_padding_mask: Optional[Tensor] = None,
104
+ pos: Optional[Tensor] = None):
105
+ '''
106
+ src.shape, pos.shape: [1024, bs, hidden_dim]
107
+ mask: None
108
+ src_key_padding_mask.shape: [bs, 1024]
109
+ '''
110
+ output = src
111
+
112
+ for layer in self.layers:
113
+ output = layer(output, src_mask=mask,
114
+ src_key_padding_mask=src_key_padding_mask, pos=pos)
115
+
116
+ if self.norm is not None:
117
+ output = self.norm(output)
118
+
119
+ return output
120
+
121
+
122
+ class TransformerDecoder(nn.Module):
123
+
124
+ def __init__(self, decoder_layer, num_layers, norm=None, return_intermediate=False):
125
+ super().__init__()
126
+ self.layers = nn.ModuleList(decoder_layer)
127
+ self.num_layers = num_layers
128
+ self.norm = norm
129
+ self.return_intermediate = return_intermediate
130
+
131
+ def forward(self, grid, h_w, tgt, memory,
132
+ tgt_mask: Optional[Tensor] = None,
133
+ memory_mask: Optional[Tensor] = None,
134
+ tgt_key_padding_mask: Optional[Tensor] = None,
135
+ memory_key_padding_mask: Optional[Tensor] = None,
136
+ pos: Optional[Tensor] = None,
137
+ query_pos: Optional[Tensor] = None, images = None, img_path = None):
138
+ output = tgt
139
+
140
+ intermediate = []
141
+
142
+ points = []
143
+ point_sigmoid_ref = None
144
+ for layer in self.layers:
145
+ # output, point, point_sigmoid_ref = layer(
146
+ # grid, h_w, output, memory, tgt_mask=tgt_mask,
147
+ # memory_mask=memory_mask, tgt_key_padding_mask=tgt_key_padding_mask,
148
+ # memory_key_padding_mask=memory_key_padding_mask,
149
+ # pos=pos, query_pos=query_pos, point_ref_previous=point_sigmoid_ref
150
+ # )
151
+
152
+ output = layer(
153
+ grid, h_w, output, memory, tgt_mask=tgt_mask,
154
+ memory_mask=memory_mask, tgt_key_padding_mask=tgt_key_padding_mask,
155
+ memory_key_padding_mask=memory_key_padding_mask,
156
+ pos=pos, query_pos=query_pos, point_ref_previous=point_sigmoid_ref, images=images, img_path = img_path
157
+ )
158
+ # points.append(point)
159
+ if self.return_intermediate:
160
+ intermediate.append(self.norm(output))
161
+
162
+ if self.norm is not None:
163
+ output = self.norm(output)
164
+ if self.return_intermediate:
165
+ intermediate.pop()
166
+ intermediate.append(output)
167
+
168
+ if self.return_intermediate:
169
+ return torch.stack(intermediate), points[0]
170
+
171
+ return output
172
+
173
+
174
+ class TransformerEncoderLayer(nn.Module):
175
+
176
+ def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,
177
+ activation="relu", normalize_before=False):
178
+ super().__init__()
179
+ self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
180
+ # Implementation of Feedforward model
181
+ self.linear1 = nn.Linear(d_model, dim_feedforward)
182
+ self.dropout = nn.Dropout(dropout)
183
+ self.linear2 = nn.Linear(dim_feedforward, d_model)
184
+
185
+ self.norm1 = nn.LayerNorm(d_model)
186
+ self.norm2 = nn.LayerNorm(d_model)
187
+ self.dropout1 = nn.Dropout(dropout)
188
+ self.dropout2 = nn.Dropout(dropout)
189
+
190
+ self.activation = _get_activation_fn(activation)
191
+ self.normalize_before = normalize_before
192
+
193
+ def with_pos_embed(self, tensor, pos: Optional[Tensor]):
194
+ return tensor if pos is None else tensor + pos
195
+
196
+ def forward_post(self,
197
+ src,
198
+ src_mask: Optional[Tensor] = None,
199
+ src_key_padding_mask: Optional[Tensor] = None,
200
+ pos: Optional[Tensor] = None):
201
+ q = k = self.with_pos_embed(src, pos)
202
+ src2 = self.self_attn(q, k, value=src, attn_mask=src_mask,
203
+ key_padding_mask=src_key_padding_mask)[0]
204
+ src = src + self.dropout1(src2)
205
+ src = self.norm1(src)
206
+ src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))
207
+ src = src + self.dropout2(src2)
208
+ src = self.norm2(src)
209
+ return src
210
+
211
+ def forward_pre(self, src,
212
+ src_mask: Optional[Tensor] = None,
213
+ src_key_padding_mask: Optional[Tensor] = None,
214
+ pos: Optional[Tensor] = None):
215
+ '''
216
+ src.shape, pos.shape: [1024, bs, hidden_dim]
217
+ src_mask: None
218
+ src_key_padding_mask.shape: [bs, 1024]
219
+ '''
220
+ src2 = self.norm1(src) # .shape: [1024, bs, hidden_dim]
221
+ q = k = self.with_pos_embed(src2, pos) # 将pos添加到feature map上
222
+ src2 = self.self_attn(q, k, value=src2, attn_mask=src_mask,
223
+ key_padding_mask=src_key_padding_mask)[0] # .shape: [1024, bs, hidden_dim]
224
+ src = src + self.dropout1(src2)
225
+ src2 = self.norm2(src)
226
+ src2 = self.linear2(self.dropout(self.activation(self.linear1(src2))))
227
+ src = src + self.dropout2(src2)
228
+ return src
229
+
230
+ def forward(self, src,
231
+ src_mask: Optional[Tensor] = None,
232
+ src_key_padding_mask: Optional[Tensor] = None,
233
+ pos: Optional[Tensor] = None):
234
+ if self.normalize_before:
235
+ return self.forward_pre(src, src_mask, src_key_padding_mask, pos)
236
+ return self.forward_post(src, src_mask, src_key_padding_mask, pos)
237
+
238
+
239
+ class TransformerDecoderLayer(nn.Module):
240
+
241
+ def __init__(self, dynamic_scale, smooth, layer_index,
242
+ d_model, nhead, dim_feedforward=2048, dropout=0.1,
243
+ activation="relu", normalize_before=False):
244
+ super().__init__()
245
+ self.wavelettransformer = WaveletTransformer()
246
+ # self.fft = FFT()
247
+ # self.dct = DCT()
248
+ self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
249
+ self.multihead_attn = GaussianMultiheadAttention(d_model, nhead, dropout=dropout)
250
+ # Implementation of Feedforward model
251
+ self.linear1 = nn.Linear(d_model, dim_feedforward)
252
+ self.dropout = nn.Dropout(dropout)
253
+ self.linear2 = nn.Linear(dim_feedforward, d_model)
254
+
255
+ self.smooth = smooth
256
+ self.dynamic_scale = dynamic_scale
257
+
258
+ self.norm1 = nn.LayerNorm(d_model)
259
+ self.norm2 = nn.LayerNorm(d_model)
260
+ self.norm3 = nn.LayerNorm(d_model)
261
+ # self.norm4 = nn.LayerNorm(d_model)
262
+ self.dropout1 = nn.Dropout(dropout)
263
+ self.dropout2 = nn.Dropout(dropout)
264
+ self.dropout3 = nn.Dropout(dropout)
265
+
266
+ # if layer_index == 0:
267
+ # self.point1 = MLP(d_model, d_model, 2, 3)
268
+ # self.point2 = nn.Linear(d_model, 2*nhead)
269
+ # else:
270
+ # self.point2 = nn.Linear(d_model, 2*nhead)
271
+ self.layer_index = layer_index
272
+ # if self.dynamic_scale == "type2":
273
+ # self.point3 = nn.Linear(d_model, nhead)
274
+ # elif self.dynamic_scale == "type3":
275
+ # self.point3 = nn.Linear(d_model, 2*nhead)
276
+ # elif self.dynamic_scale == "type4":
277
+ # self.point3 = nn.Linear(d_model, 3*nhead)
278
+
279
+ self.activation = _get_activation_fn(activation)
280
+ self.normalize_before = normalize_before
281
+
282
+ self.nhead = nhead
283
+
284
+ def with_pos_embed(self, tensor, pos: Optional[Tensor]):
285
+ return tensor if pos is None else tensor + pos
286
+
287
+ def forward_post(self, grid, h_w, tgt, memory,
288
+ tgt_mask: Optional[Tensor] = None,
289
+ memory_mask: Optional[Tensor] = None,
290
+ tgt_key_padding_mask: Optional[Tensor] = None,
291
+ memory_key_padding_mask: Optional[Tensor] = None,
292
+ pos: Optional[Tensor] = None,
293
+ query_pos: Optional[Tensor] = None,
294
+ point_ref_previous: Optional[Tensor] = None):
295
+ tgt_len = tgt.shape[0]
296
+
297
+ out = self.norm4(tgt + query_pos)
298
+ point_sigmoid_offset = self.point2(out)
299
+
300
+ q = k = self.with_pos_embed(tgt, query_pos)
301
+ tgt2 = self.self_attn(q, k, value=tgt, attn_mask=tgt_mask,
302
+ key_padding_mask=tgt_key_padding_mask)[0]
303
+ tgt = tgt + self.dropout1(tgt2)
304
+ tgt = self.norm1(tgt)
305
+
306
+ if self.layer_index == 0:
307
+ point_sigmoid_ref_inter = self.point1(out)
308
+ point_sigmoid_ref = point_sigmoid_ref_inter.sigmoid()
309
+ point_sigmoid_ref = (h_w - 0) * point_sigmoid_ref / int((h_w.max().item()/int(grid.max()+1)))
310
+ point_sigmoid_ref = point_sigmoid_ref.repeat(1, 1, self.nhead)
311
+ else:
312
+ point_sigmoid_ref = point_ref_previous
313
+
314
+ point = point_sigmoid_ref + point_sigmoid_offset
315
+ point = point.view(tgt_len, -1, 2)
316
+ distance = (point.unsqueeze(1) - grid.unsqueeze(0)).pow(2)
317
+
318
+ if self.dynamic_scale == "type1":
319
+ scale = 1
320
+ distance = distance.sum(-1) * scale
321
+ elif self.dynamic_scale == "type2":
322
+ scale = self.point3(out)
323
+ scale = scale * scale
324
+ scale = scale.reshape(tgt_len, -1).unsqueeze(1)
325
+ distance = distance.sum(-1) * scale
326
+ elif self.dynamic_scale == "type3":
327
+ scale = self.point3(out)
328
+ scale = scale * scale
329
+ scale = scale.reshape(tgt_len, -1, 2).unsqueeze(1)
330
+ distance = (distance * scale).sum(-1)
331
+ elif self.dynamic_scale == "type4":
332
+ scale = self.point3(out)
333
+ scale = scale * scale
334
+ scale = scale.reshape(tgt_len, -1, 3).unsqueeze(1)
335
+ distance = torch.cat([distance, torch.prod(distance, dim=-1, keepdim=True)], dim=-1)
336
+ distance = (distance * scale).sum(-1)
337
+
338
+ gaussian = -(distance - 0).abs() / self.smooth
339
+
340
+ tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt, query_pos),
341
+ key=self.with_pos_embed(memory, pos),
342
+ value=memory, attn_mask=memory_mask,
343
+ key_padding_mask=memory_key_padding_mask,
344
+ gaussian=[gaussian])[0]
345
+ tgt = tgt + self.dropout2(tgt2)
346
+ tgt = self.norm2(tgt)
347
+ tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt))))
348
+ tgt = tgt + self.dropout3(tgt2)
349
+ tgt = self.norm3(tgt)
350
+ if self.layer_index == 0:
351
+ return tgt, point_sigmoid_ref_inter, point_sigmoid_ref
352
+ else:
353
+ return tgt, None, point_sigmoid_ref
354
+
355
+ def forward_pre(self, grid, h_w, tgt, memory,
356
+ tgt_mask: Optional[Tensor] = None,
357
+ memory_mask: Optional[Tensor] = None,
358
+ tgt_key_padding_mask: Optional[Tensor] = None,
359
+ memory_key_padding_mask: Optional[Tensor] = None,
360
+ pos: Optional[Tensor] = None,
361
+ query_pos: Optional[Tensor] = None,
362
+ point_ref_previous: Optional[Tensor] = None,
363
+ idx = -1, images=None, img_path = None):
364
+ '''
365
+ grid.shape: [1024, bs * nhead, 2]
366
+ tgt.shape, query_pos.shape: [5, bs, hidden_dim]
367
+ '''
368
+
369
+ # tgt_len = tgt.shape[0]
370
+ # out = self.norm4(tgt + query_pos)
371
+ # point_sigmoid_offset = self.point2(out) # Δt .shape: [5, bs, 2 * nhead]
372
+
373
+ tgt2 = self.norm1(tgt)
374
+ q = k = self.with_pos_embed(tgt2, query_pos)
375
+ tgt2 = self.self_attn(q, k, value=tgt2, attn_mask=tgt_mask,
376
+ key_padding_mask=tgt_key_padding_mask)[0] # .shape: [5, bs, hidden_dim]
377
+ tgt = tgt + self.dropout1(tgt2)
378
+
379
+ # if self.layer_index == 0:
380
+ # point_sigmoid_ref_inter = self.point1(out) # .shape: [5, bs, 2]
381
+ # point_sigmoid_ref = point_sigmoid_ref_inter.sigmoid()
382
+ # point_sigmoid_ref = (h_w - 0) * point_sigmoid_ref / int((h_w.max().item()/int(grid.max()+1)))
383
+ # point_sigmoid_ref = point_sigmoid_ref.repeat(1, 1, self.nhead) # [5, bs, 2 * nhead]
384
+ # else:
385
+ # point_sigmoid_ref = point_ref_previous # t .shape: [5, bs, 2 * nhead]
386
+
387
+ # point = point_sigmoid_ref + point_sigmoid_offset
388
+ # point = point.view(tgt_len, -1, 2) # .shape: [5, bs * nhead, 2]
389
+ # distance = (point.unsqueeze(1) - grid.unsqueeze(0)).pow(2) # distance.shape: [5, 1024, bs * nhead, 2] = [5, 1, bs * nhead, 2] - [1, 1024, bs * nhead, 2]
390
+
391
+ # if self.dynamic_scale == "type1":
392
+ # scale = 1
393
+ # distance = distance.sum(-1) * scale
394
+ # elif self.dynamic_scale == "type2":
395
+ # scale = self.point3(out)
396
+ # scale = scale * scale
397
+ # scale = scale.reshape(tgt_len, -1).unsqueeze(1)
398
+ # distance = distance.sum(-1) * scale
399
+ # elif self.dynamic_scale == "type3":
400
+ # scale = self.point3(out) # .shape: [5, bs, 2 * nhead]
401
+ # scale = scale * scale
402
+ # scale = scale.reshape(tgt_len, -1, 2).unsqueeze(1) # .shape: [5, 1, bs * nhead, 2]
403
+ # distance = (distance * scale).sum(-1) # distance.shape = [5, 1024, bs * nhead]
404
+ # elif self.dynamic_scale == "type4":
405
+ # scale = self.point3(out)
406
+ # scale = scale * scale
407
+ # scale = scale.reshape(tgt_len, -1, 3).unsqueeze(1)
408
+ # distance = torch.cat([distance, torch.prod(distance, dim=-1, keepdim=True)], dim=-1)
409
+ # distance = (distance * scale).sum(-1)
410
+
411
+ # gaussian = -(distance - 0).abs() / self.smooth # .shape: [5, 1024, bs * nhead]
412
+
413
+ gaussian = self.wavelettransformer(images).permute(1, 0).repeat(5, 1, self.nhead) # .shape: [5, 1024, bs * nhead]
414
+ # gaussian = self.fft(images).permute(1, 0).repeat(5, 1, self.nhead)
415
+ # gaussian = self.dct(images).permute(1, 0).repeat(5, 1, self.nhead)
416
+
417
+ # gaussian[gaussian < (torch.max(gaussian) + torch.min(gaussian)) / 2] = 0
418
+ # pdb.set_trace()
419
+
420
+ tgt2 = self.norm2(tgt)
421
+ tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt2, query_pos),
422
+ key=self.with_pos_embed(memory, pos),
423
+ value=memory, attn_mask=memory_mask,
424
+ key_padding_mask=memory_key_padding_mask,
425
+ gaussian=[gaussian],
426
+ idx = idx, images=images, img_path = img_path)[0]
427
+
428
+ # 生成attention map
429
+ # attn_out_weights_ = attn_out_weights[0][0][0]
430
+
431
+ tgt = tgt + self.dropout2(tgt2)
432
+ tgt2 = self.norm3(tgt)
433
+ tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))
434
+ tgt = tgt + self.dropout3(tgt2)
435
+
436
+ # if self.layer_index == 0:
437
+ # return tgt, point_sigmoid_ref_inter, point_sigmoid_ref
438
+ # else:
439
+ # return tgt, None, point_sigmoid_ref
440
+ return tgt
441
+
442
+ def forward(self, grid, h_w, tgt, memory,
443
+ tgt_mask: Optional[Tensor] = None,
444
+ memory_mask: Optional[Tensor] = None,
445
+ tgt_key_padding_mask: Optional[Tensor] = None,
446
+ memory_key_padding_mask: Optional[Tensor] = None,
447
+ pos: Optional[Tensor] = None,
448
+ query_pos: Optional[Tensor] = None,
449
+ point_ref_previous: Optional[Tensor] = None, images=None, img_path = None):
450
+ if self.normalize_before:
451
+ return self.forward_pre(grid, h_w, tgt, memory, tgt_mask, memory_mask,
452
+ tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos,
453
+ point_ref_previous, self.layer_index, images=images, img_path = img_path)
454
+ return self.forward_post(grid, h_w, tgt, memory, tgt_mask, memory_mask,
455
+ tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos,
456
+ point_ref_previous)
457
+
458
+
459
+ # 定义一个包含卷积和池化的网络
460
+ class ConvNet(nn.Module):
461
+ def __init__(self):
462
+ super(ConvNet, self).__init__()
463
+
464
+ # 第一个卷积层,输入9个通道,输出64个通道,卷积核大小3x3,步幅1,填充1
465
+ self.conv1 = nn.Conv2d(9, 64, kernel_size=3, stride=1, padding=1)
466
+ self.pool = nn.MaxPool2d(kernel_size=2, stride=2) # 池化操作,每次池化减半空间尺寸
467
+
468
+ # 第二个卷积层,输入64个通道,输出128个通道,卷积核大小3x3,步幅1,填充1
469
+ self.conv2 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)
470
+
471
+ # 第三个卷积层,输入128个通道,输出1个通道,卷积核大小3x3,步幅1,填充1
472
+ self.conv3 = nn.Conv2d(128, 1, kernel_size=3, stride=1, padding=1)
473
+
474
+ def forward(self, x):
475
+ x = self.pool(self.conv1(x)) # (1, 9, 256, 256) -> (1, 64, 256, 256) -> (1, 64, 128, 128)
476
+ x = self.pool(self.conv2(x)) # (1, 64, 128, 128) -> (1, 128, 128, 128) -> (1, 128, 64, 64)
477
+ x = self.pool(self.conv3(x)) # (1, 128, 64, 64) -> (1, 1, 64, 64) -> (1, 1, 32, 32)
478
+
479
+ return x.flatten(0) # (1024,)
480
+
481
+
482
+ class WaveletTransformer(nn.Module):
483
+ def __init__(self):
484
+ super().__init__()
485
+ # self.ConvNet = ConvNet()
486
+ self.xfm = DWTForward(J=1, mode='zero', wave='haar').cuda() # Accepts all wave types available to PyWavelets
487
+ self.xfm.requires_grad_ = False
488
+ self.conv = nn.Conv2d(3, 1, kernel_size=3, stride=1, padding=1)
489
+ self.pool = nn.AdaptiveAvgPool2d((32, 32))
490
+
491
+ # def forward(self, images):
492
+ # # images.shapes: [bs, 3, 512, 512]
493
+ # batch_size = images.shape[0]
494
+ # # 预先分配输出张量
495
+ # coeffs = torch.zeros(batch_size, 1024).cuda()
496
+ # for i in range(batch_size):
497
+ # # pdb.set_trace()
498
+ # wave = self.wavelet(images[i])
499
+ # # coeffs[i] = self.ConvNet(wave)
500
+ # coeffs[i] = self.pool(self.conv(wave)).flatten(0)
501
+ # # pdb.set_trace()
502
+ # return coeffs # .shape: [bs, 1024]
503
+
504
+ # def wavelet(self, image):
505
+ # #J为分解的层次数,wave表示使用的变换方法
506
+ # _, Yh = self.xfm(image.unsqueeze(0))
507
+ # # pdb.set_trace()
508
+
509
+ # # h = torch.cat((Yh[0][:,:,0,:,:], Yh[0][:,:,1,:,:], Yh[0][:,:,2,:,:]), dim=1)
510
+ # h = Yh[0][:, :, 2, :, :] # .shape: [1, 3, 256, 256]
511
+
512
+ # return h
513
+
514
+ def forward(self, images):
515
+ # 输入 images.shape: [B, 3, 512, 512]
516
+
517
+ # 批量小波变换
518
+ wave = self.wavelet_batch(images) # 输出 [B, 3, 256, 256]
519
+
520
+ # 并行卷积和池化
521
+ coeffs = self.pool(self.conv(wave)).flatten(1) # 直接处理整个batch
522
+
523
+ return coeffs # 输出 [B, 1024]
524
+
525
+ def wavelet_batch(self, images):
526
+ # 批量处理版本
527
+ _, Yh = self.xfm(images) # 保持输入为完整batch
528
+
529
+ # 直接批量索引操作
530
+ return Yh[0][:, :, 2, :, :] # 输出 [B, 3, 256, 256]
531
+
532
+
533
+ class MLP(nn.Module):
534
+ """ Very simple multi-layer perceptron (also called FFN)"""
535
+
536
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
537
+ super().__init__()
538
+ self.num_layers = num_layers
539
+ h = [hidden_dim] * (num_layers - 1)
540
+ self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
541
+
542
+ def forward(self, x):
543
+ for i, layer in enumerate(self.layers):
544
+ x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
545
+ return x
546
+
547
+
548
+ def _get_clones(module, N):
549
+ return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
550
+
551
+
552
+ class DecoderEmbeddings(nn.Module):
553
+ def __init__(self, config):
554
+ super().__init__()
555
+ self.word_embeddings = nn.Embedding(
556
+ config.vocab_size, config.hidden_dim, padding_idx=config.PAD_token_id)
557
+ # self.clip_text_embeddings = FrozenCLIPEmbedder(max_length=10)
558
+
559
+ self.position_embeddings = nn.Embedding(
560
+ config.max_position_embeddings, config.hidden_dim
561
+ )
562
+ # self.projection_layer = nn.Linear(768, config.hidden_dim)
563
+ # self.clip_layernorm = nn.LayerNorm(config.hidden_dim, eps=config.layer_norm_eps)
564
+
565
+ self.LayerNorm = torch.nn.LayerNorm(
566
+ config.hidden_dim, eps=config.layer_norm_eps)
567
+ self.dropout = nn.Dropout(config.dropout)
568
+
569
+ def forward(self, x):
570
+ # pdb.set_trace()
571
+ input_shape = x.size() # x.size(): [bs, 5]
572
+ # seq_length = input_shape[1]
573
+ # device = x.device
574
+
575
+ position_ids = torch.arange(
576
+ input_shape[1], dtype=torch.long, device=x.device)
577
+ position_ids = position_ids.unsqueeze(0).expand(input_shape)
578
+
579
+ input_embeds = self.word_embeddings(x) # .shape: [bs, 5, hidden_dim]
580
+ # input_embeds = self.clip_text_embeddings(x) # .shape: [bs, 5, 768]
581
+ # TODO: init
582
+ # input_embeds = self.projection_layer(input_embeds) # .shape: [bs, 5, hidden_dim]
583
+ # input_embeds = self.clip_layernorm(input_embeds)
584
+
585
+ position_embeds = self.position_embeddings(position_ids) # .shape: [bs, 5, hidden_dim]
586
+ # position_embeds = self.LayerNorm(position_embeds)
587
+
588
+ embeddings = input_embeds + position_embeds
589
+ embeddings = self.LayerNorm(embeddings)
590
+ embeddings = self.dropout(embeddings)
591
+
592
+ return embeddings
593
+
594
+
595
+ # 得到下半部分全为0,上半部分全为'-inf'的矩阵
596
+ def generate_square_subsequent_mask(sz):
597
+ r"""Generate a square mask for the sequence. The masked positions are filled with float('-inf').
598
+ Unmasked positions are filled with float(0.0).
599
+ """
600
+ mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1) # triu: 获取矩阵的上三角部分
601
+ mask = mask.float().masked_fill(mask == 0, float(
602
+ '-inf')).masked_fill(mask == 1, float(0.0))
603
+ return mask # .shape: [sz, sz]
604
+
605
+
606
+ def build_transformer(config):
607
+ return Transformer(
608
+ config,
609
+ d_model=config.hidden_dim,
610
+ dropout=config.dropout,
611
+ nhead=config.nheads,
612
+ dim_feedforward=config.dim_feedforward,
613
+ num_encoder_layers=config.enc_layers,
614
+ num_decoder_layers=config.dec_layers,
615
+ normalize_before=config.pre_norm,
616
+ return_intermediate_dec=False,
617
+ smooth=config.smooth,
618
+ dynamic_scale=config.dynamic_scale,
619
+ )
620
+
621
+
622
+ def _get_activation_fn(activation):
623
+ """Return an activation function given a string"""
624
+ if activation == "relu":
625
+ return F.relu
626
+ if activation == "gelu":
627
+ return F.gelu
628
+ if activation == "glu":
629
+ return F.glu
630
+ raise RuntimeError(F"activation should be relu/gelu, not {activation}.")
FAITH/pytorch_wavelets/.travis.yml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ language: python
2
+ # Run in a container
3
+ dist: trusty
4
+ sudo: false
5
+ python:
6
+ - "3.5"
7
+ - "3.6"
8
+ #Command to install dependencies
9
+ git:
10
+ depth: 1
11
+ install:
12
+ - pip install --quiet -r tests/requirements.txt
13
+ - pip install .
14
+ script: pytest
FAITH/pytorch_wavelets/LICENSE ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ This licence applies to any parts of this library which are novel in comparison
2
+ to the original DTCWT MATLAB toolbox written by Nick Kingsbury and Cian
3
+ Shaffrey. See the Provenance section of README.rst file for details on any further
4
+ restrictions of use. If you wish to use the DTCWT, you should read that license as well.
5
+ The DWT sections come under this license.
6
+
7
+ MIT License
8
+
9
+ Copyright (c) 2020 Fergal Cotter
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+