Anhforth commited on
Commit
86c77fb
1 Parent(s): 1ce16c2

updatde readme

Browse files

Signed-off-by: Anhforth <yanzhaodong2021@163.com>

Files changed (1) hide show
  1. README.md +420 -0
README.md CHANGED
@@ -1,3 +1,423 @@
1
  ---
2
  license: apache-2.0
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: apache-2.0
3
  ---
4
+
5
+
6
+
7
+
8
+ # AltCLIPTextEncoder
9
+
10
+ - Github: [FlaAI](https://github.com/FlagAI-Open/FlagAI)
11
+ - Language(s): Chinese, English
12
+ - Task: Text encoding
13
+ - Size: 3.22G
14
+
15
+ ## 简介 Brief Introduction
16
+
17
+ 我们提出了一个简单高效的方法去训练更加优秀的双语CLIP模型。命名为AltCLIP。AltCLIP基于 [Stable Diffusiosn](https://github.com/CompVis/stable-diffusion) 训练,训练数据来自 [WuDao数据集](https://data.baai.ac.cn/details/WuDaoCorporaText) 和 [LIAON](https://huggingface.co/datasets/ChristophSchuhmann/improved_aesthetics_6plus)
18
+
19
+ AltCLIP模型可以为本项目中的AltDiffusion模型提供支持,关于AltDiffusion模型的具体信息可查看[此教程](https://github.com/FlagAI-Open/FlagAI/tree/master/examples/AltDiffusion/README.md) 。
20
+
21
+ 模型代码已经在 [FlagAI](https://github.com/FlagAI-Open/FlagAI/tree/master/examples/AltCLIP) 上开源,权重位于我们搭建的 [modelhub](https://model.baai.ac.cn/model-detail/100075) 上。我们还提供了微调,推理,验证的脚本,欢迎试用。
22
+
23
+
24
+ We propose a simple and efficient method to train a better bilingual CLIP model. Named AltCLIP. AltCLIP is trained based on [Stable Diffusiosn](https://github.com/CompVis/stable-diffusion) with training data from [WuDao dataset](https://data.baai.ac.cn/details/WuDaoCorporaText) and [Liaon](https://huggingface.co/datasets/laion/laion2B-en).
25
+
26
+ The AltCLIP model can provide support for the AltDiffusion model in this project. Specific information on the AltDiffusion model can be found in [this tutorial](https://github.com/FlagAI-Open/FlagAI/tree/master/examples/AltDiffusion/README.md).
27
+
28
+ The model code has been open sourced on [FlagAI](https://github.com/FlagAI-Open/FlagAI/tree/master/examples/AltCLIP) and the weights are located on [modelhub](https://model.baai.ac.cn/model-detail/100075). We also provide scripts for fine-tuning, inference, and validation, so feel free to try them out.
29
+
30
+
31
+
32
+ ## 训练 Training
33
+
34
+ 训练共有两个阶段。
35
+ 在平行知识蒸馏阶段,我们只是使用平行语料文本来进行蒸馏(平行语料相对于图文对更容易获取且数量更大)。在双语对比学习阶段,我们使用少量的中-英 图像-文本对(一共约2百万)来训练我们的文本编码器以更好地适应图像编码器。
36
+
37
+ There are two phases of training.
38
+ In the parallel knowledge distillation phase, we only use parallel corpus texts for distillation (parallel corpus is easier to obtain and larger in number compared to image text pairs). In the bilingual comparison learning phase, we use a small number of Chinese-English image-text pairs (about 2 million in total) to train our text encoder to better fit the image encoder.
39
+
40
+
41
+
42
+ ## 下游效果 Performance
43
+
44
+ <table>
45
+ <tr>
46
+ <td rowspan=2>Language</td>
47
+ <td rowspan=2>Method</td>
48
+ <td colspan=3>Text-to-Image Retrival</td>
49
+ <td colspan=3>Image-to-Text Retrival</td>
50
+ <td rowspan=2>MR</td>
51
+ </tr>
52
+ <tr>
53
+ <td>R@1</td>
54
+ <td>R@5</td>
55
+ <td>R@10</td>
56
+ <td>R@1</td>
57
+ <td>R@5</td>
58
+ <td>R@10</td>
59
+ </tr>
60
+ <tr>
61
+ <td rowspan=7>English</td>
62
+ <td>CLIP</td>
63
+ <td>65.0 </td>
64
+ <td>87.1 </td>
65
+ <td>92.2 </td>
66
+ <td>85.1 </td>
67
+ <td>97.3 </td>
68
+ <td>99.2 </td>
69
+ <td>87.6 </td>
70
+ </tr>
71
+ <tr>
72
+ <td>Taiyi</td>
73
+ <td>25.3 </td>
74
+ <td>48.2 </td>
75
+ <td>59.2 </td>
76
+ <td>39.3 </td>
77
+ <td>68.1 </td>
78
+ <td>79.6 </td>
79
+ <td>53.3 </td>
80
+ </tr>
81
+ <tr>
82
+ <td>Wukong</td>
83
+ <td>-</td>
84
+ <td>-</td>
85
+ <td>-</td>
86
+ <td>-</td>
87
+ <td>-</td>
88
+ <td>-</td>
89
+ <td>-</td>
90
+ </tr>
91
+ <tr>
92
+ <td>R2D2</td>
93
+ <td>-</td>
94
+ <td>-</td>
95
+ <td>-</td>
96
+ <td>-</td>
97
+ <td>-</td>
98
+ <td>-</td>
99
+ <td>-</td>
100
+ </tr>
101
+ <tr>
102
+ <td>CN-CLIP</td>
103
+ <td>49.5 </td>
104
+ <td>76.9 </td>
105
+ <td>83.8 </td>
106
+ <td>66.5 </td>
107
+ <td>91.2 </td>
108
+ <td>96.0 </td>
109
+ <td>77.3 </td>
110
+ </tr>
111
+ <tr>
112
+ <td>AltCLIP</td>
113
+ <td>66.3 </td>
114
+ <td>87.8 </td>
115
+ <td>92.7 </td>
116
+ <td>85.9 </td>
117
+ <td>97.7 </td>
118
+ <td>99.1 </td>
119
+ <td>88.3 </td>
120
+ </tr>
121
+ <tr>
122
+ <td>AltCLIP∗</td>
123
+ <td>72.5 </td>
124
+ <td>91.6 </td>
125
+ <td>95.4 </td>
126
+ <td>86.0 </td>
127
+ <td>98.0 </td>
128
+ <td>99.1 </td>
129
+ <td>90.4 </td>
130
+ </tr>
131
+ <tr>
132
+ <td rowspan=7>Chinese</td>
133
+ <td>CLIP</td>
134
+ <td>0.0 </td>
135
+ <td>2.4 </td>
136
+ <td>4.0 </td>
137
+ <td>2.3 </td>
138
+ <td>8.1 </td>
139
+ <td>12.6 </td>
140
+ <td>5.0 </td>
141
+ </tr>
142
+ <tr>
143
+ <td>Taiyi</td>
144
+ <td>53.7 </td>
145
+ <td>79.8 </td>
146
+ <td>86.6 </td>
147
+ <td>63.8 </td>
148
+ <td>90.5 </td>
149
+ <td>95.9 </td>
150
+ <td>78.4 </td>
151
+ </tr>
152
+ <tr>
153
+ <td>Wukong</td>
154
+ <td>51.7 </td>
155
+ <td>78.9 </td>
156
+ <td>86.3 </td>
157
+ <td>76.1 </td>
158
+ <td>94.8 </td>
159
+ <td>97.5 </td>
160
+ <td>80.9 </td>
161
+ </tr>
162
+ <tr>
163
+ <td>R2D2</td>
164
+ <td>60.9 </td>
165
+ <td>86.8 </td>
166
+ <td>92.7 </td>
167
+ <td>77.6 </td>
168
+ <td>96.7 </td>
169
+ <td>98.9 </td>
170
+ <td>85.6 </td>
171
+ </tr>
172
+ <tr>
173
+ <td>CN-CLIP</td>
174
+ <td>68.0 </td>
175
+ <td>89.7 </td>
176
+ <td>94.4 </td>
177
+ <td>80.2 </td>
178
+ <td>96.6 </td>
179
+ <td>98.2 </td>
180
+ <td>87.9 </td>
181
+ </tr>
182
+ <tr>
183
+ <td>AltCLIP</td>
184
+ <td>63.7 </td>
185
+ <td>86.3 </td>
186
+ <td>92.1 </td>
187
+ <td>84.7 </td>
188
+ <td>97.4 </td>
189
+ <td>98.7 </td>
190
+ <td>87.2 </td>
191
+ </tr>
192
+ <tr>
193
+ <td>AltCLIP∗</td>
194
+ <td>69.8 </td>
195
+ <td>89.9 </td>
196
+ <td>94.7 </td>
197
+ <td>84.8 </td>
198
+ <td>97.4 </td>
199
+ <td>98.8 </td>
200
+ <td>89.2 </td>
201
+ </tr>
202
+ </table>
203
+
204
+ ![image-20221111172255521](https://raw.githubusercontent.com/920232796/test/master/image.png)
205
+
206
+
207
+
208
+
209
+ ## 可视化效果 Visualization effects
210
+
211
+ 基于AltCLIP,我们还开发了AltDiffusion模型,可视化效果如下。
212
+
213
+ Based on AltCLIP, we have also developed the AltDiffusion model, visualized as follows.
214
+
215
+ ![](https://raw.githubusercontent.com/920232796/test/master/image7.png)
216
+
217
+ ## 模型推理 Inference
218
+
219
+ ```python
220
+ import torch
221
+ from PIL import Image
222
+ from flagai.auto_model.auto_loader import AutoLoader
223
+
224
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
225
+ ## 一行代码直接自动下载权重到'./checkpoints/clip-xlmr-large',并自动加载CLIP模型权重
226
+ ## modelhub地址: Modelhub(https://model.baai.ac.cn/models)
227
+ loader = AutoLoader(
228
+ task_name="txt_img_matching",
229
+ model_dir="./checkpoints",
230
+ model_name="AltCLIP-XLMR-L"
231
+ )
232
+ ## 获取加载好的模型
233
+ model = loader.get_model()
234
+ ## 获取tokenizer
235
+ tokenizer = loader.get_tokenizer()
236
+ ## 获取transform用来处理图像
237
+ transform = loader.get_transform()
238
+
239
+ model.eval()
240
+ model.to(device)
241
+
242
+ ## 推理过程,图像与文本匹配
243
+ image = Image.open("./dog.jpeg")
244
+ image = transform(image)
245
+ image = torch.tensor(image["pixel_values"]).to(device)
246
+ text = tokenizer(["a rat", "a dog", "a cat"])["input_ids"]
247
+
248
+ text = torch.tensor(text).to(device)
249
+
250
+ with torch.no_grad():
251
+ image_features = model.get_image_features(image)
252
+ text_features = model.get_text_features(text)
253
+ text_probs = (image_features @ text_features.T).softmax(dim=-1)
254
+
255
+ print(text_probs.cpu().numpy()[0].tolist())
256
+ ```
257
+
258
+ ## CLIP微调 Finetuning
259
+
260
+ 微调采用cifar10数据集,并使用FlagAI的Trainer快速开始训练过程。
261
+
262
+ Fine-tuning was done using the cifar10 dataset and using FlagAI's Trainer to quickly start the training process.
263
+
264
+ ```python
265
+ # Copyright © 2022 BAAI. All rights reserved.
266
+ #
267
+ # Licensed under the Apache License, Version 2.0 (the "License")
268
+ import torch
269
+ from flagai.auto_model.auto_loader import AutoLoader
270
+ import os
271
+ from flagai.trainer import Trainer
272
+ from torchvision.datasets import (
273
+ CIFAR10
274
+ )
275
+
276
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
277
+ dataset_root = "./clip_benchmark_datasets"
278
+ dataset_name = "cifar10"
279
+
280
+ batch_size = 4
281
+ classes = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
282
+
283
+ auto_loader = AutoLoader(
284
+ task_name="txt_img_matching",
285
+ model_dir="./checkpoints/",
286
+ model_name="AltCLIP-XLMR-L" # Load the checkpoints from Modelhub(model.baai.ac.cn/models)
287
+ )
288
+
289
+ model = auto_loader.get_model()
290
+ model.to(device)
291
+ model.eval()
292
+ tokenizer = auto_loader.get_tokenizer()
293
+ transform = auto_loader.get_transform()
294
+
295
+ trainer = Trainer(env_type="pytorch",
296
+ pytorch_device=device,
297
+ experiment_name="clip_finetuning",
298
+ batch_size=4,
299
+ lr=1e-4,
300
+ epochs=10,
301
+ log_interval=10)
302
+
303
+ dataset = CIFAR10(root=os.path.join(dataset_root, dataset_name),
304
+ transform=transform,
305
+ download=True)
306
+
307
+ def cifar10_collate_fn(batch):
308
+ # image shape is (batch, 3, 224, 224)
309
+ images = torch.tensor([b[0]["pixel_values"][0] for b in batch])
310
+ # text_id shape is (batch, n)
311
+ input_ids = torch.tensor([tokenizer(f"a photo of a {b[1]}",padding=True,truncation=True,max_length=77)["input_ids"] for b in batch])
312
+
313
+ return {
314
+ "pixel_values": images,
315
+ "input_ids": input_ids
316
+ }
317
+
318
+ if __name__ == "__main__":
319
+ trainer.train(model=model, train_dataset=dataset, collate_fn=cifar10_collate_fn)
320
+ ```
321
+
322
+
323
+
324
+ ## 模型验证 Evaluation
325
+
326
+ 我们提供了可以直接运行的验证脚本,在cifar10数据集上进行验证。
327
+
328
+ 期待的输出为:```{'dataset': 'cifar10', 'metrics': {'acc1': 0.95402, 'acc5': 0.99616, 'mean_per_class_recall': 0.9541200000000002}}```
329
+
330
+ We provide validation scripts that can be run directly on the cifar10 dataset.
331
+
332
+ ```python
333
+ # Copyright © 2022 BAAI. All rights reserved.
334
+ #
335
+ # Licensed under the Apache License, Version 2.0 (the "License")
336
+ import torch
337
+ from flagai.auto_model.auto_loader import AutoLoader
338
+ from metrics import zeroshot_classification
339
+ import json
340
+ import os
341
+ from torchvision.datasets import CIFAR10
342
+
343
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
344
+ maxlen = 256
345
+
346
+ dataset_root = "./clip_benchmark_datasets"
347
+ dataset_name = "cifar10"
348
+
349
+ auto_loader = AutoLoader(
350
+ task_name="txt_img_matching",
351
+ model_dir="./checkpoints/",
352
+ model_name="AltCLIP-XLMR-L"
353
+ )
354
+
355
+ model = auto_loader.get_model()
356
+ model.to(device)
357
+ model.eval()
358
+ tokenizer = auto_loader.get_tokenizer()
359
+ transform = auto_loader.get_transform()
360
+
361
+ dataset = CIFAR10(root=os.path.join(dataset_root, dataset_name),
362
+ transform=transform,
363
+ download=True)
364
+ batch_size = 128
365
+ num_workers = 4
366
+
367
+ template = {"cifar10": [
368
+ "a photo of a {c}.",
369
+ "a blurry photo of a {c}.",
370
+ "a black and white photo of a {c}.",
371
+ "a low contrast photo of a {c}.",
372
+ "a high contrast photo of a {c}.",
373
+ "a bad photo of a {c}.",
374
+ "a good photo of a {c}.",
375
+ "a photo of a small {c}.",
376
+ "a photo of a big {c}.",
377
+ "a photo of the {c}.",
378
+ "a blurry photo of the {c}.",
379
+ "a black and white photo of the {c}.",
380
+ "a low contrast photo of the {c}.",
381
+ "a high contrast photo of the {c}.",
382
+ "a bad photo of the {c}.",
383
+ "a good photo of the {c}.",
384
+ "a photo of the small {c}.",
385
+ "a photo of the big {c}."
386
+ ],
387
+ }
388
+ def evaluate():
389
+ if dataset:
390
+ dataloader = torch.utils.data.DataLoader(
391
+ dataset,
392
+ batch_size=batch_size,
393
+ shuffle=False,
394
+ num_workers=num_workers,
395
+ )
396
+ classnames = dataset.classes if hasattr(dataset, "classes") else None
397
+
398
+ zeroshot_templates = template["cifar10"]
399
+ metrics = zeroshot_classification.evaluate(
400
+ model,
401
+ dataloader,
402
+ tokenizer,
403
+ classnames,
404
+ zeroshot_templates,
405
+ device=device,
406
+ amp=True,
407
+ )
408
+
409
+ dump = {
410
+ "dataset": dataset_name,
411
+ "metrics": metrics
412
+ }
413
+
414
+ print(dump)
415
+ with open("./result.txt", "w") as f:
416
+ json.dump(dump, f)
417
+ return metrics
418
+
419
+ if __name__ == "__main__":
420
+ evaluate()
421
+
422
+ ```
423
+