1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
|
%global _empty_manifest_terminate_build 0
Name: python-clip-retrieval
Version: 2.36.1
Release: 1
Summary: Easily computing clip embeddings and building a clip retrieval system with them
License: MIT
URL: https://github.com/rom1504/clip-retrieval
Source0: https://mirrors.nju.edu.cn/pypi/web/packages/2b/3d/88db2730bb2460c7565a6acc44d8bb10c0b3c9b41dda31bb8f868e440a3f/clip_retrieval-2.36.1.tar.gz
BuildArch: noarch
Requires: python3-img2dataset
Requires: python3-clip-anytorch
Requires: python3-tqdm
Requires: python3-fire
Requires: python3-torch
Requires: python3-torchvision
Requires: python3-numpy
Requires: python3-faiss-cpu
Requires: python3-flask
Requires: python3-flask-restful
Requires: python3-flask-cors
Requires: python3-pandas
Requires: python3-pyarrow
Requires: python3-autofaiss
Requires: python3-webdataset
Requires: python3-h5py
Requires: python3-prometheus-client
Requires: python3-fsspec
Requires: python3-sentence-transformers
Requires: python3-wandb
Requires: python3-open-clip-torch
Requires: python3-requests
Requires: python3-aiohttp
Requires: python3-multilingual-clip
%description
# clip-retrieval
[](https://pypi.python.org/pypi/clip-retrieval)
[](http://badge.fury.io/js/clip-retrieval-front)
[](https://colab.research.google.com/github/rom1504/clip-retrieval/blob/master/notebook/clip-retrieval-getting-started.ipynb)
[](https://gitpod.io/#https://github.com/rom1504/clip-retrieval)
[](https://discord.gg/eq3cAMZtCC)
Easily compute clip embeddings and build a clip retrieval system with them. 100M text+image embeddings can be processed in 20h using a 3080.
* clip client allows remote querying of backend via python. [clip-client notebook](https://colab.research.google.com/github/rom1504/clip-retrieval/blob/master/notebook/clip-client-query-api.ipynb)
* clip inference allows you to quickly (1500 sample/s on a 3080) compute image and text embeddings
* clip index builds efficient indices out of the embeddings
* clip filter allows you to filter out the data using the clip index
* clip back hosts the indices with a simple flask service
* clip front is a simple ui querying the back. Check it out at [clip-retrieval ui](https://rom1504.github.io/clip-retrieval/)
* clip end2end runs img2dataset, inference, index then back and front to make all of this easier to begin with
End to end this make it possible to build a simple semantic search system.
Interested to learn about semantic search in general ? You can read my [medium post](https://rom1504.medium.com/semantic-search-with-embeddings-index-anything-8fb18556443c) on the topic.
Also see [laion5B](https://laion.ai/laion-5b-a-new-era-of-open-large-scale-multi-modal-datasets/) and [semantic search at billions scale](https://rom1504.medium.com/semantic-search-at-billions-scale-95f21695689a) to read more on how to make this scale to billion of samples.
[<img src="https://github.com/rom1504/clip-retrieval/raw/main/doc_assets/clip-front-pic.png" alt="clip front" width="500">](https://rom1504.github.io/clip-retrieval/)
## Who is using clip retrieval ?
* [cah-prepro](https://github.com/rom1504/cah-prepro) preprocess the 400M image+text crawling at home dataset. clip-retrieval is used to compute 400M clip embeddings and the indices
* [autofaiss](https://github.com/criteo/autofaiss) uses clip-retrieval to display an example of use (see the multimodal notebook example there)
* [afiaka87 openai demo](https://gist.github.com/afiaka87/f662486fc45199fa4394f3456c8246d7#file-dalle_blog_semantic_search-ipynb) shows how to look among the 1M example released by openai for their DALL-E demo
* [antarctic-captions by dzryk](https://github.com/dzryk/antarctic-captions) uses autofaiss and clip inference as a way to generate anchors for the image to text task with great success
## Install
pip install clip-retrieval
If your interest it to run the laion5B index, see [this doc](docs/laion5B_back.md)
## Clip client
`ClipClient` allows remote querying of a clip-retrieval backend via python.
See [`ClipClient` - Getting Started Notebook](/notebook/clip-client-query-api.ipynb) for a jupyter notebook example.
### API Initialization
During initialization you can specify a few parameters:
* `backend_url`: the url of the backend. (required)
* `indice_name`: specify the name of the index you want to use. (required)
* `aesthetic_score`: the aesthetic score as rated by [aesthetic_detector](https://github.com/rom1504/aesthetic_detector). Default is `9`.
* `use_mclip`: whether to use a multi-lingual version of CLIP. Default is `False`.
* `aesthetic_weight`: the weight of the aesthetic score. Default is `0.5`
* `modality`: search over image or text in the index, one of `Multimodal.IMAGE` or `Multimodal.TEXT`. Default is `Multimodal.IMAGE`.
* `num_images`: the number of images to return from the API. Default is `40`.
* `deduplicate`: Whether to deduplicate the result by image embedding. Default is true.
* `use_safety_model`: Whether to remove unsafe images. Default is true.
* `use_violence_detector`: Whether to remove images with violence. Default is true.
For instance, to query the hosted backend for Laion5B with the default parameters:
```python
from clip_retrieval.clip_client import ClipClient, Modality
client = ClipClient(url="https://knn5.laion.ai/knn-service", indice_name="laion5B")
```
### Query by text
You can find captioned images similar to the text you provide.
```python
results = client.query(text="an image of a cat")
results[0]
> {'url': 'https://example.com/kitten.jpg', 'caption': 'an image of a kitten', 'id': 14, 'similarity': 0.2367108941078186}
```
### Query by image
You can also find captioned images similar to the image you provide. Images can be passed via local path or url.
```python
cat_results = client.query(image="cat.jpg")
dog_results = client.query(image="https://example.com/dog.jpg")
```
### Query by embedding
You can also find captioned images similar to a clip embedding you provide.
```python
cat_results = client.query(embedding_input=cat_embedding)
```
### Query a directory of images
To enhance an existing dataset with similar text/image pairs, you can query a directory of images and combine the results.
```python
all_results = [result for result in [client.query(image=image) for image in os.listdir("my-images")]]
with open("search-results.json", "w") as f:
json.dump(all_results, f)
```
### Create a dataset
You can create a dataset using the saved json results and the tool `img2dataset`.
```sh
img2dataset "search-results.json" \
--input_format="json" \
--output_folder="knn_search_dataset" \
--caption_col="caption"
```
## clip end2end
First pick a dataset of image urls and captions ([examples](https://github.com/rom1504/img2dataset/tree/main/examples)) then run:
You may want to run `export CUDA_VISIBLE_DEVICES=` to avoid using your GPU if it doesn't have enough VRAM.
```
wget https://github.com/rom1504/img2dataset/raw/main/tests/test_1000.parquet
clip-retrieval end2end test_1000.parquet /tmp/my_output
```
Then go to [http://localhost:1234](http://localhost:1234) and enjoy searching among your pictures
Use `--run_back False` if you don't want to run the backend
## clip inference
Get some images in an `example_folder`, for example by doing:
```
pip install img2dataset
echo 'https://placekitten.com/200/305' >> myimglist.txt
echo 'https://placekitten.com/200/304' >> myimglist.txt
echo 'https://placekitten.com/200/303' >> myimglist.txt
img2dataset --url_list=myimglist.txt --output_folder=image_folder --thread_count=64 --image_size=256
```
You can also put text files with the same names as the images in that folder, to get the text embeddings.
Then run `clip-retrieval inference --input_dataset image_folder --output_folder embeddings_folder`
Output folder will contain:
* img_emb/
* img_emb_0.npy containing the image embeddings as numpy
* text_emb/
* text_emb_0.npy containing the text embeddings as numpy
* metadata/
* metadata_0.parquet containing the image paths, captions and metadata
This scales to million of samples. At 1400 sample/s of a 3080, 10M samples can be processed in 2h.
### API
clip_inference turn a set of text+image into clip embeddings
* **input_dataset** Path to input dataset. Folder if input_format is files. Bash brace pattern such as "{000..150}.tar" (see https://pypi.org/project/braceexpand/) if webdataset (*required*)
* **output_folder** Folder where the clip embeddings will be saved, as well as metadata (*required*)
* **input_format** files or webdataset (default *files*)
* **cache_path** cache path for webdataset (default *None*)
* **batch_size** Number of items to do the inference on at once (default *256*)
* **num_prepro_workers** Number of processes to do the preprocessing (default *8*)
* **enable_text** Enable text processing (default *True*)
* **enable_image** Enable image processing (default *True*)
* **enable_metadata** Enable metadata processing (default *False*)
* **write_batch_size** Write batch size (default *10**6*)
* **wds_image_key** Key to use for images in webdataset. (default *jpg*)
* **wds_caption_key** Key to use for captions in webdataset. (default *txt*)
* **clip_model** CLIP model to load (default *ViT-B/32*). Specify it as `"open_clip:ViT-B-32-quickgelu"` to use the [open_clip](https://github.com/mlfoundations/open_clip).
* **mclip_model** MCLIP model to load (default *sentence-transformers/clip-ViT-B-32-multilingual-v1*)
* **use_mclip** If False it performs the inference using CLIP; MCLIP otherwise (default *False*)
* **use_jit** uses jit for the clip model (default *True*)
* **distribution_strategy** choose how to distribute the job, see distribution section for details (default *sequential*)
* **wds_number_file_per_input_file** estimation of the number of sample per tar if using wds and not specifying output_partition_count (default *10000*)
* **output_partition_count** number of output partitions (default *None*)
* **wandb_project** wandb project to use (default *clip_retrieval*)
* **enable_wandb** whether to use wandb (default *False*)
* **clip_cache_path** cache path for clip (default *None*)
* **slurm_job_name**, the job name to use in slurm. (default *None*)
* **slurm_partition** (default *None*), the slurm partition to create a job in.
* **slurm_jobs**, the number of jobs to create in slurm. (default *None*)
* **slurm_job_comment**, the job comment to use. (default *None*)
* **slurm_nodelist**, a list of specific nodes to use .(default *None*
* **slurm_exclude**, a list of nodes to exclude when creating jobs. (default *None*)
* **slurm_job_timeout**, if not supplied it will default to 2 weeks. (default *None*)
* **slurm_cache_path**, cache path to use for slurm-related tasks. (default *None*)
* **slurm_verbose_wait=False**, wether to print the status of your slurm job (default *False*)
### Inference Worker
If you wish to have more control over how inference is run, you can create and call workers directly using `clip-retrieval inference.worker`
Example Usage:
```bash
clip-retrieval inference.worker \
--tasks="[0]" \
--input_dataset="input/folder/{000000..000100}.tar" \
--output_folder="example/path" \
--input_format="webdataset" \
--output_partition_count="1"
```
Doing so will invoke a single worker that can be instructed to focus on a specific subset of the `input_dataset`. That worker will sequentially process the `tasks` passed to it. Here, `tasks` is a lists of `partition_id`'s that this worker will be responsible for.
To manually compute the number of tasks, use the following formula: `number_samples / wds_number_file_per_input_file`.
The API is very similar to `clip-retrieval inference` with some minor changes:
* **tasks** A list of integers representing the `partition_id`'s that this worker is responsible for computing. (*required*)
* **input_dataset** Path to input dataset. Folder if input_format is files. Bash brace pattern such as "{000..150}.tar" (see https://pypi.org/project/braceexpand/) if webdataset (*required*)
* **output_folder** Folder where the clip embeddings will be saved, as well as metadata (*required*)
* **output_partition_count** number of output partitions (*required*)
* **input_format** files or webdataset (default *files*)
* **cache_path** cache path for webdataset (default *None*)
* **batch_size** Number of items to do the inference on at once (default *256*)
* **num_prepro_workers** Number of processes to do the preprocessing (default *8*)
* **enable_text** Enable text processing (default *True*)
* **enable_image** Enable image processing (default *True*)
* **enable_metadata** Enable metadata processing (default *False*)
* **wds_image_key** Key to use for images in webdataset. (default *jpg*)
* **wds_caption_key** Key to use for captions in webdataset. (default *txt*)
* **clip_model** CLIP model to load (default *ViT-B/32*). Specify it as `"open_clip:ViT-B-32-quickgelu"` to use the [open_clip](https://github.com/mlfoundations/open_clip).
* **mclip_model** MCLIP model to load (default *sentence-transformers/clip-ViT-B-32-multilingual-v1*)
* **use_mclip** If False it performs the inference using CLIP; MCLIP otherwise (default *False*)
* **use_jit** uses jit for the clip model (default *True*)
* **wandb_project** wandb project to use (default *clip_retrieval*)
* **enable_wandb** whether to use wandb (default *False*)
* **clip_cache_path** cache path for clip (default *None*)
> ***Note***: The worker does not accept the following arguments
> * **write_batch_size** Write batch size (default *10**6*)
> * **distribution_strategy** choose how to distribute the job, see distribution section for details (default *sequential*)
> * **wds_number_file_per_input_file** estimation of the number of sample per tar if using wds and not specifying output_partition_count (default *10000*)
> * **any of the SLURM arguments**
### Loading/writing files on hdfs
- To load a webdataset from a hdfs folder, set --input_dataset "pipe:hdfs dfs -cat path_on_hdfs" in the request without the "hdfs://" prefix.
- To write the output on hdfs, set --output_hdfs_folder to the path on hdfs prefixed by "hdfs://"
Example of hdfs query using webdataset format:
`clip_inference --input_dataset "pipe:hdfs dfs -cat /myfolder/webdataset/{00000..00010}.tar" --output_folder "hdfs://myfolder/embeddings" --input_format webdataset
### Loading/writing files on s3
`clip_inference --input_dataset "pipe:aws s3 cp --quiet s3://myfolder/webdataset/{00000..00010}.tar -" --output_folder "s3://myfolder/embeddings" --input_format webdataset
### Distributed inference
To run this on multiple nodes (and multiple gpus), see tutorial at [docs/distributed_clip_inference.md](docs/distributed_clip_inference.md)
## Clip index
Clip index takes as input the output of clip inference and makes an index out of it using [autofaiss](https://github.com/criteo/autofaiss)
`clip-retrieval index --embeddings_folder embeddings_folder --index_folder index_folder`
* `--max_index_memory_usage "16G"` option allow configuring the amount of ram the index will consume. More ram, better knn recall (Default `4G`).
* `--current_memory_available 24G` allows controlling how much ram is used during the creation process (Default `16G`).
* `--image_subfolder "img_emb"` allows to specify a subfolder for the image embeddings which is concatenated to the `--embeddings_folder` option (Default `img_emb`).
* `--text_subfolder "text_emb"` allows to specify a subfolder for the text embeddings which is concatenated to the `--embeddings_folder` option (Default `text_emb`).
* `--copy_metadata True` makes it possible to choose whether to copy metadata or not at the end of the process (Default `True`).
* `--nb_cores 8` allows controlling the number of threads (Default `None`, which will use all cores).
The output is a folder containing:
* image.index containing a faiss index for images
* text.index containing a faiss index for texts
* metadata folder containing the parquet metadata
Thanks to autofaiss and faiss, this scales to hundred of million of samples in a few hours.
You may want to carefully pick how much memory to use for your index in order to maximize the knn recall.
[autofaiss index selection colab](https://colab.research.google.com/github/criteo/autofaiss/blob/master/docs/notebooks/autofaiss_index_selection_demo.ipynb) can help along with `autofaiss score_index` command to check the recall of your index. In general indices using more memory get a better recall and hence are closer to a naive (slow) knn
## Clip filter
Once the embeddings are computed, you may want to filter out the data by a specific query.
For that you can run `clip-retrieval filter --query "cat" --output_folder "cat/" --indice_folder "indice_folder"`
It will copy the 100 best images for this query in the output folder.
Using the `--num_results` or `--threshold` may be helpful to refine the filter
Thanks to fast knn index, this can run in real time (<10ms) for large K values (100000), and in minutes for very large K values.
This scripts works for small datasets. For larger ones, please check [notebook/simple_filter.ipynb].
## Clip back
Clip back is a simple knn service backend. If using both hdf5 and faiss memory mapping, it uses only the memory used by clip which is 4GB.
Run (output_folder is the output of clip index)
```bash
echo '{"example_index": "output_folder"}' > indices_paths.json
clip-retrieval back --port 1234 --indices-paths indices_paths.json
```
Options:
* `--use_jit True` uses jit for the clip model
* `--clip_model "ViT-B/32"` allows choosing the clip model to use. Prefix with `"open_clip:"` to use an [open_clip](https://github.com/mlfoundations/open_clip) model.
* `--enable_mclip_option True` loads the mclip model, making it possible to search in any language.
* `--columns_to_return='["url", "image_path", "caption", "NSFW"]` allows you to specify which columns should be fetched from the metadata and returned by the backend. It's useful to specify less in case of hdf5 caching to speed up the queries.
* `--enable_faiss_memory_mapping=True` option can be passed to use an index with memory mapping.
That decreases the memory usage to zero.
* `--enable_hdf5 True` option can be passed to enable hdf5 caching for the metadata.
HDF5 caching makes it possible to use the metadata with almost no memory usage.
* `--use_arrow True` allows using arrow instead of hdf5. Should be used along with [clip_back_prepro](clip_back_prepro) for very large datasets (billions)
* `--reorder_metadata_by_ivf_index True` option takes advantage of the data locality property of results of a knn ivf indices: it orders the metadata collection in order of the IVF clusters. That makes it possible to have much faster metadata retrieval as the reads are then accessing a few mostly sequential parts of the metadata instead of many non sequential parts. In practice that means being able to retrieve 1M items in 1s whereas only 1000 items can be retrieved in 1s without this method. This will order the metadata using the first image index.
* `--provide_safety_model True` will automatically download and load a [safety model](https://github.com/LAION-AI/CLIP-based-NSFW-Detector). You need to `pip install autokeras` optional dependency for this to work.
* `--provide_violence_detector True` will load a [violence detector](https://github.com/ml-research/OffImgDetectionCLIP), [paper](https://arxiv.org/abs/2202.06675.pdf)
* `--provide_aesthetic_embeddings True` will load the [aesthetic embeddings](https://github.com/LAION-AI/aesthetic-predictor) and allow users to make the query move towards a nicer point of the clip space
These options can also be provided in the config file to have different options for each index. Example:
```json
{
"laion5B": {
"indice_folder": "/mnt/laion5B/prepared_data",
"provide_safety_model": true,
"enable_faiss_memory_mapping": true,
"use_arrow": true,
"enable_hdf5": false,
"reorder_metadata_by_ivf_index": false,
"columns_to_return": ["url", "caption"],
"clip_model": "ViT-L/14",
"enable_mclip_option": false
},
"laion_400m": {
"indice_folder": "/mnt/laion400M/index100",
"provide_safety_model": true,
"enable_faiss_memory_mapping": true,
"enable_hdf5": true,
"use_arrow": false,
"reorder_metadata_by_ivf_index": true,
"enable_mclip_option": true,
"clip_model": "ViT-B/32"
}
}
```
hdf5 or arrow caching is a good idea to use if:
* you do not have enough ram to load the metadata in memory
* your disk is fast (ie you have a ssd)
At this point you have a simple flask server running on port 1234 and that can answer these queries:
* `/indices-list` -> return a list of indices
* `/knn-service` that takes as input:
```js
{
"text": "a text query",
"image": "a base64 image",
"image_url": "http://some-url.com/a.jpg",
"modality": "image", // image or text index to use
"num_images": 4, // number of output images
"indice_name": "example_index",
"num_result_ids": 4 // optional, if specified fetch this number of results in total but only num_images with metadata
}
```
text, image and image_url are mutually exclusive
and returns:
```js
[
{
"image": "base 64 of an image",
"text": "some result text",
"id": 543
},
{
"image": "base 64 of an image",
"text": "some result text",
"id": 782
}
]
```
Each object may also contain an url field if the metadata provides it.
The id is the position of the item in the index. It may be used to query metadata with the /metadata endpoint:
```js
{
"indice_name": "example_index",
"ids": [543, 782]
}
```
which returns:
```js
{
"image": "base 64 of an image",
"text": "some result text"
// any other key available in the metadata and specified in columns_to_return cli option
}
```
`num_result_ids` argument of `/knn-service` and `/metadata` can be used together to do large knn queries and then fetch the metadata only when needed. It makes sense to do that as knn search can be very efficient thanks to strong [locality of reference](https://en.wikipedia.org/wiki/Locality_of_reference) of knn IVF index making it fast to do knn with a large K, whereas the current on-disk implementation of metadata (hdf5) does not have that property and hence cannot handle retrieving a large amount of random items fast.
In particular this can be used to implement infinite scroll in a front end.
By default the backend will also expose a front end. That front end will by default hit this backend, however you may need to specify whether this is happening over http or https, in this case use the option `--default_backend` to specify the backend url. `--url_column` allows specifying the name of the column url for the front
### Clip back: Benchmark and monitoring
This backends has a 50ms latency if using memory mapped indices and metadata. Throughput is about 20 query/s. For high throughput, using a grpc server is required as well as a GPU for fast clip inference, turning off memory mapping options can also speed up requests, at the cost of high ram usage.
This backends also exposes a prometheus `/metrics` endpoint as well as an human readable summary at `/metrics-summary`.
This can (optionally) be used to setup a [grafana dashboard](doc_assets/grafana_dashboard.json) for monitoring:
[<img src="https://github.com/rom1504/clip-retrieval/raw/main/doc_assets/clip-back-grafana.png" alt="grafana" width="1200">](https://github.com/rom1504/clip-retrieval/raw/main/doc_assets/clip-back-grafana.png)
It can be seen on this dashboard that the slowest part of any call is fetching the image by its url in case of image url search, taking up to 300ms.
For text queries or image queries, the latency is about 50ms.
Here is an example of output in the metrics summary:
```
Among 20.0 calls to the knn end point with an average latency of 0.1889s per request, the step costs are (in order):
name description calls average proportion
0 download_time Time spent downloading an url 6 0.3215s 170.2%
1 metadata_get_time Time spent retrieving metadata 20 0.0415s 21.9%
2 knn_index_time Time spent doing a knn on the index 20 0.0267s 14.1%
3 image_clip_inference_time Time spent doing a image clip inference 6 0.0206s 10.9%
4 text_clip_inference_time Time spent doing a text clip inference 14 0.0186s 9.8%
5 image_prepro_time Time spent doing the image preprocessing 6 0.0097s 5.2%
6 text_prepro_time Time spent doing the text preprocessing 14 0.0020s 1.0%
```
## clip-front
Clip front is a simple UI that connects to clip back and display the results.
You can use it at [clip-retrieval ui](https://rom1504.github.io/clip-retrieval/)
Or you can run it yourself with:
```
npm install -g clip-retrieval-front
clip-retrieval-front 3005
```
You can also run it with `clip-retrieval front` or back from the python package.
### Development
For development it, go to [front](front) and run `npm install` then `npm start`.
## For development
Either locally, or in [gitpod](https://gitpod.io/#https://github.com/rom1504/clip-retrieval) (do `export PIP_USER=false` there)
Setup a virtualenv:
```
python3 -m venv .env
source .env/bin/activate
pip install -e .
```
to run tests:
```
pip install -r requirements-test.txt
```
then
```
make lint
make test
```
You can use `make black` to reformat the code
`python -m pytest -x -s -v tests -k "test_runner"` to run a specific test
If you want to use the front through the python backend or frontend, run
```
cd front
npm install
npm run build
cd ..
pip install -e .
```
%package -n python3-clip-retrieval
Summary: Easily computing clip embeddings and building a clip retrieval system with them
Provides: python-clip-retrieval
BuildRequires: python3-devel
BuildRequires: python3-setuptools
BuildRequires: python3-pip
%description -n python3-clip-retrieval
# clip-retrieval
[](https://pypi.python.org/pypi/clip-retrieval)
[](http://badge.fury.io/js/clip-retrieval-front)
[](https://colab.research.google.com/github/rom1504/clip-retrieval/blob/master/notebook/clip-retrieval-getting-started.ipynb)
[](https://gitpod.io/#https://github.com/rom1504/clip-retrieval)
[](https://discord.gg/eq3cAMZtCC)
Easily compute clip embeddings and build a clip retrieval system with them. 100M text+image embeddings can be processed in 20h using a 3080.
* clip client allows remote querying of backend via python. [clip-client notebook](https://colab.research.google.com/github/rom1504/clip-retrieval/blob/master/notebook/clip-client-query-api.ipynb)
* clip inference allows you to quickly (1500 sample/s on a 3080) compute image and text embeddings
* clip index builds efficient indices out of the embeddings
* clip filter allows you to filter out the data using the clip index
* clip back hosts the indices with a simple flask service
* clip front is a simple ui querying the back. Check it out at [clip-retrieval ui](https://rom1504.github.io/clip-retrieval/)
* clip end2end runs img2dataset, inference, index then back and front to make all of this easier to begin with
End to end this make it possible to build a simple semantic search system.
Interested to learn about semantic search in general ? You can read my [medium post](https://rom1504.medium.com/semantic-search-with-embeddings-index-anything-8fb18556443c) on the topic.
Also see [laion5B](https://laion.ai/laion-5b-a-new-era-of-open-large-scale-multi-modal-datasets/) and [semantic search at billions scale](https://rom1504.medium.com/semantic-search-at-billions-scale-95f21695689a) to read more on how to make this scale to billion of samples.
[<img src="https://github.com/rom1504/clip-retrieval/raw/main/doc_assets/clip-front-pic.png" alt="clip front" width="500">](https://rom1504.github.io/clip-retrieval/)
## Who is using clip retrieval ?
* [cah-prepro](https://github.com/rom1504/cah-prepro) preprocess the 400M image+text crawling at home dataset. clip-retrieval is used to compute 400M clip embeddings and the indices
* [autofaiss](https://github.com/criteo/autofaiss) uses clip-retrieval to display an example of use (see the multimodal notebook example there)
* [afiaka87 openai demo](https://gist.github.com/afiaka87/f662486fc45199fa4394f3456c8246d7#file-dalle_blog_semantic_search-ipynb) shows how to look among the 1M example released by openai for their DALL-E demo
* [antarctic-captions by dzryk](https://github.com/dzryk/antarctic-captions) uses autofaiss and clip inference as a way to generate anchors for the image to text task with great success
## Install
pip install clip-retrieval
If your interest it to run the laion5B index, see [this doc](docs/laion5B_back.md)
## Clip client
`ClipClient` allows remote querying of a clip-retrieval backend via python.
See [`ClipClient` - Getting Started Notebook](/notebook/clip-client-query-api.ipynb) for a jupyter notebook example.
### API Initialization
During initialization you can specify a few parameters:
* `backend_url`: the url of the backend. (required)
* `indice_name`: specify the name of the index you want to use. (required)
* `aesthetic_score`: the aesthetic score as rated by [aesthetic_detector](https://github.com/rom1504/aesthetic_detector). Default is `9`.
* `use_mclip`: whether to use a multi-lingual version of CLIP. Default is `False`.
* `aesthetic_weight`: the weight of the aesthetic score. Default is `0.5`
* `modality`: search over image or text in the index, one of `Multimodal.IMAGE` or `Multimodal.TEXT`. Default is `Multimodal.IMAGE`.
* `num_images`: the number of images to return from the API. Default is `40`.
* `deduplicate`: Whether to deduplicate the result by image embedding. Default is true.
* `use_safety_model`: Whether to remove unsafe images. Default is true.
* `use_violence_detector`: Whether to remove images with violence. Default is true.
For instance, to query the hosted backend for Laion5B with the default parameters:
```python
from clip_retrieval.clip_client import ClipClient, Modality
client = ClipClient(url="https://knn5.laion.ai/knn-service", indice_name="laion5B")
```
### Query by text
You can find captioned images similar to the text you provide.
```python
results = client.query(text="an image of a cat")
results[0]
> {'url': 'https://example.com/kitten.jpg', 'caption': 'an image of a kitten', 'id': 14, 'similarity': 0.2367108941078186}
```
### Query by image
You can also find captioned images similar to the image you provide. Images can be passed via local path or url.
```python
cat_results = client.query(image="cat.jpg")
dog_results = client.query(image="https://example.com/dog.jpg")
```
### Query by embedding
You can also find captioned images similar to a clip embedding you provide.
```python
cat_results = client.query(embedding_input=cat_embedding)
```
### Query a directory of images
To enhance an existing dataset with similar text/image pairs, you can query a directory of images and combine the results.
```python
all_results = [result for result in [client.query(image=image) for image in os.listdir("my-images")]]
with open("search-results.json", "w") as f:
json.dump(all_results, f)
```
### Create a dataset
You can create a dataset using the saved json results and the tool `img2dataset`.
```sh
img2dataset "search-results.json" \
--input_format="json" \
--output_folder="knn_search_dataset" \
--caption_col="caption"
```
## clip end2end
First pick a dataset of image urls and captions ([examples](https://github.com/rom1504/img2dataset/tree/main/examples)) then run:
You may want to run `export CUDA_VISIBLE_DEVICES=` to avoid using your GPU if it doesn't have enough VRAM.
```
wget https://github.com/rom1504/img2dataset/raw/main/tests/test_1000.parquet
clip-retrieval end2end test_1000.parquet /tmp/my_output
```
Then go to [http://localhost:1234](http://localhost:1234) and enjoy searching among your pictures
Use `--run_back False` if you don't want to run the backend
## clip inference
Get some images in an `example_folder`, for example by doing:
```
pip install img2dataset
echo 'https://placekitten.com/200/305' >> myimglist.txt
echo 'https://placekitten.com/200/304' >> myimglist.txt
echo 'https://placekitten.com/200/303' >> myimglist.txt
img2dataset --url_list=myimglist.txt --output_folder=image_folder --thread_count=64 --image_size=256
```
You can also put text files with the same names as the images in that folder, to get the text embeddings.
Then run `clip-retrieval inference --input_dataset image_folder --output_folder embeddings_folder`
Output folder will contain:
* img_emb/
* img_emb_0.npy containing the image embeddings as numpy
* text_emb/
* text_emb_0.npy containing the text embeddings as numpy
* metadata/
* metadata_0.parquet containing the image paths, captions and metadata
This scales to million of samples. At 1400 sample/s of a 3080, 10M samples can be processed in 2h.
### API
clip_inference turn a set of text+image into clip embeddings
* **input_dataset** Path to input dataset. Folder if input_format is files. Bash brace pattern such as "{000..150}.tar" (see https://pypi.org/project/braceexpand/) if webdataset (*required*)
* **output_folder** Folder where the clip embeddings will be saved, as well as metadata (*required*)
* **input_format** files or webdataset (default *files*)
* **cache_path** cache path for webdataset (default *None*)
* **batch_size** Number of items to do the inference on at once (default *256*)
* **num_prepro_workers** Number of processes to do the preprocessing (default *8*)
* **enable_text** Enable text processing (default *True*)
* **enable_image** Enable image processing (default *True*)
* **enable_metadata** Enable metadata processing (default *False*)
* **write_batch_size** Write batch size (default *10**6*)
* **wds_image_key** Key to use for images in webdataset. (default *jpg*)
* **wds_caption_key** Key to use for captions in webdataset. (default *txt*)
* **clip_model** CLIP model to load (default *ViT-B/32*). Specify it as `"open_clip:ViT-B-32-quickgelu"` to use the [open_clip](https://github.com/mlfoundations/open_clip).
* **mclip_model** MCLIP model to load (default *sentence-transformers/clip-ViT-B-32-multilingual-v1*)
* **use_mclip** If False it performs the inference using CLIP; MCLIP otherwise (default *False*)
* **use_jit** uses jit for the clip model (default *True*)
* **distribution_strategy** choose how to distribute the job, see distribution section for details (default *sequential*)
* **wds_number_file_per_input_file** estimation of the number of sample per tar if using wds and not specifying output_partition_count (default *10000*)
* **output_partition_count** number of output partitions (default *None*)
* **wandb_project** wandb project to use (default *clip_retrieval*)
* **enable_wandb** whether to use wandb (default *False*)
* **clip_cache_path** cache path for clip (default *None*)
* **slurm_job_name**, the job name to use in slurm. (default *None*)
* **slurm_partition** (default *None*), the slurm partition to create a job in.
* **slurm_jobs**, the number of jobs to create in slurm. (default *None*)
* **slurm_job_comment**, the job comment to use. (default *None*)
* **slurm_nodelist**, a list of specific nodes to use .(default *None*
* **slurm_exclude**, a list of nodes to exclude when creating jobs. (default *None*)
* **slurm_job_timeout**, if not supplied it will default to 2 weeks. (default *None*)
* **slurm_cache_path**, cache path to use for slurm-related tasks. (default *None*)
* **slurm_verbose_wait=False**, wether to print the status of your slurm job (default *False*)
### Inference Worker
If you wish to have more control over how inference is run, you can create and call workers directly using `clip-retrieval inference.worker`
Example Usage:
```bash
clip-retrieval inference.worker \
--tasks="[0]" \
--input_dataset="input/folder/{000000..000100}.tar" \
--output_folder="example/path" \
--input_format="webdataset" \
--output_partition_count="1"
```
Doing so will invoke a single worker that can be instructed to focus on a specific subset of the `input_dataset`. That worker will sequentially process the `tasks` passed to it. Here, `tasks` is a lists of `partition_id`'s that this worker will be responsible for.
To manually compute the number of tasks, use the following formula: `number_samples / wds_number_file_per_input_file`.
The API is very similar to `clip-retrieval inference` with some minor changes:
* **tasks** A list of integers representing the `partition_id`'s that this worker is responsible for computing. (*required*)
* **input_dataset** Path to input dataset. Folder if input_format is files. Bash brace pattern such as "{000..150}.tar" (see https://pypi.org/project/braceexpand/) if webdataset (*required*)
* **output_folder** Folder where the clip embeddings will be saved, as well as metadata (*required*)
* **output_partition_count** number of output partitions (*required*)
* **input_format** files or webdataset (default *files*)
* **cache_path** cache path for webdataset (default *None*)
* **batch_size** Number of items to do the inference on at once (default *256*)
* **num_prepro_workers** Number of processes to do the preprocessing (default *8*)
* **enable_text** Enable text processing (default *True*)
* **enable_image** Enable image processing (default *True*)
* **enable_metadata** Enable metadata processing (default *False*)
* **wds_image_key** Key to use for images in webdataset. (default *jpg*)
* **wds_caption_key** Key to use for captions in webdataset. (default *txt*)
* **clip_model** CLIP model to load (default *ViT-B/32*). Specify it as `"open_clip:ViT-B-32-quickgelu"` to use the [open_clip](https://github.com/mlfoundations/open_clip).
* **mclip_model** MCLIP model to load (default *sentence-transformers/clip-ViT-B-32-multilingual-v1*)
* **use_mclip** If False it performs the inference using CLIP; MCLIP otherwise (default *False*)
* **use_jit** uses jit for the clip model (default *True*)
* **wandb_project** wandb project to use (default *clip_retrieval*)
* **enable_wandb** whether to use wandb (default *False*)
* **clip_cache_path** cache path for clip (default *None*)
> ***Note***: The worker does not accept the following arguments
> * **write_batch_size** Write batch size (default *10**6*)
> * **distribution_strategy** choose how to distribute the job, see distribution section for details (default *sequential*)
> * **wds_number_file_per_input_file** estimation of the number of sample per tar if using wds and not specifying output_partition_count (default *10000*)
> * **any of the SLURM arguments**
### Loading/writing files on hdfs
- To load a webdataset from a hdfs folder, set --input_dataset "pipe:hdfs dfs -cat path_on_hdfs" in the request without the "hdfs://" prefix.
- To write the output on hdfs, set --output_hdfs_folder to the path on hdfs prefixed by "hdfs://"
Example of hdfs query using webdataset format:
`clip_inference --input_dataset "pipe:hdfs dfs -cat /myfolder/webdataset/{00000..00010}.tar" --output_folder "hdfs://myfolder/embeddings" --input_format webdataset
### Loading/writing files on s3
`clip_inference --input_dataset "pipe:aws s3 cp --quiet s3://myfolder/webdataset/{00000..00010}.tar -" --output_folder "s3://myfolder/embeddings" --input_format webdataset
### Distributed inference
To run this on multiple nodes (and multiple gpus), see tutorial at [docs/distributed_clip_inference.md](docs/distributed_clip_inference.md)
## Clip index
Clip index takes as input the output of clip inference and makes an index out of it using [autofaiss](https://github.com/criteo/autofaiss)
`clip-retrieval index --embeddings_folder embeddings_folder --index_folder index_folder`
* `--max_index_memory_usage "16G"` option allow configuring the amount of ram the index will consume. More ram, better knn recall (Default `4G`).
* `--current_memory_available 24G` allows controlling how much ram is used during the creation process (Default `16G`).
* `--image_subfolder "img_emb"` allows to specify a subfolder for the image embeddings which is concatenated to the `--embeddings_folder` option (Default `img_emb`).
* `--text_subfolder "text_emb"` allows to specify a subfolder for the text embeddings which is concatenated to the `--embeddings_folder` option (Default `text_emb`).
* `--copy_metadata True` makes it possible to choose whether to copy metadata or not at the end of the process (Default `True`).
* `--nb_cores 8` allows controlling the number of threads (Default `None`, which will use all cores).
The output is a folder containing:
* image.index containing a faiss index for images
* text.index containing a faiss index for texts
* metadata folder containing the parquet metadata
Thanks to autofaiss and faiss, this scales to hundred of million of samples in a few hours.
You may want to carefully pick how much memory to use for your index in order to maximize the knn recall.
[autofaiss index selection colab](https://colab.research.google.com/github/criteo/autofaiss/blob/master/docs/notebooks/autofaiss_index_selection_demo.ipynb) can help along with `autofaiss score_index` command to check the recall of your index. In general indices using more memory get a better recall and hence are closer to a naive (slow) knn
## Clip filter
Once the embeddings are computed, you may want to filter out the data by a specific query.
For that you can run `clip-retrieval filter --query "cat" --output_folder "cat/" --indice_folder "indice_folder"`
It will copy the 100 best images for this query in the output folder.
Using the `--num_results` or `--threshold` may be helpful to refine the filter
Thanks to fast knn index, this can run in real time (<10ms) for large K values (100000), and in minutes for very large K values.
This scripts works for small datasets. For larger ones, please check [notebook/simple_filter.ipynb].
## Clip back
Clip back is a simple knn service backend. If using both hdf5 and faiss memory mapping, it uses only the memory used by clip which is 4GB.
Run (output_folder is the output of clip index)
```bash
echo '{"example_index": "output_folder"}' > indices_paths.json
clip-retrieval back --port 1234 --indices-paths indices_paths.json
```
Options:
* `--use_jit True` uses jit for the clip model
* `--clip_model "ViT-B/32"` allows choosing the clip model to use. Prefix with `"open_clip:"` to use an [open_clip](https://github.com/mlfoundations/open_clip) model.
* `--enable_mclip_option True` loads the mclip model, making it possible to search in any language.
* `--columns_to_return='["url", "image_path", "caption", "NSFW"]` allows you to specify which columns should be fetched from the metadata and returned by the backend. It's useful to specify less in case of hdf5 caching to speed up the queries.
* `--enable_faiss_memory_mapping=True` option can be passed to use an index with memory mapping.
That decreases the memory usage to zero.
* `--enable_hdf5 True` option can be passed to enable hdf5 caching for the metadata.
HDF5 caching makes it possible to use the metadata with almost no memory usage.
* `--use_arrow True` allows using arrow instead of hdf5. Should be used along with [clip_back_prepro](clip_back_prepro) for very large datasets (billions)
* `--reorder_metadata_by_ivf_index True` option takes advantage of the data locality property of results of a knn ivf indices: it orders the metadata collection in order of the IVF clusters. That makes it possible to have much faster metadata retrieval as the reads are then accessing a few mostly sequential parts of the metadata instead of many non sequential parts. In practice that means being able to retrieve 1M items in 1s whereas only 1000 items can be retrieved in 1s without this method. This will order the metadata using the first image index.
* `--provide_safety_model True` will automatically download and load a [safety model](https://github.com/LAION-AI/CLIP-based-NSFW-Detector). You need to `pip install autokeras` optional dependency for this to work.
* `--provide_violence_detector True` will load a [violence detector](https://github.com/ml-research/OffImgDetectionCLIP), [paper](https://arxiv.org/abs/2202.06675.pdf)
* `--provide_aesthetic_embeddings True` will load the [aesthetic embeddings](https://github.com/LAION-AI/aesthetic-predictor) and allow users to make the query move towards a nicer point of the clip space
These options can also be provided in the config file to have different options for each index. Example:
```json
{
"laion5B": {
"indice_folder": "/mnt/laion5B/prepared_data",
"provide_safety_model": true,
"enable_faiss_memory_mapping": true,
"use_arrow": true,
"enable_hdf5": false,
"reorder_metadata_by_ivf_index": false,
"columns_to_return": ["url", "caption"],
"clip_model": "ViT-L/14",
"enable_mclip_option": false
},
"laion_400m": {
"indice_folder": "/mnt/laion400M/index100",
"provide_safety_model": true,
"enable_faiss_memory_mapping": true,
"enable_hdf5": true,
"use_arrow": false,
"reorder_metadata_by_ivf_index": true,
"enable_mclip_option": true,
"clip_model": "ViT-B/32"
}
}
```
hdf5 or arrow caching is a good idea to use if:
* you do not have enough ram to load the metadata in memory
* your disk is fast (ie you have a ssd)
At this point you have a simple flask server running on port 1234 and that can answer these queries:
* `/indices-list` -> return a list of indices
* `/knn-service` that takes as input:
```js
{
"text": "a text query",
"image": "a base64 image",
"image_url": "http://some-url.com/a.jpg",
"modality": "image", // image or text index to use
"num_images": 4, // number of output images
"indice_name": "example_index",
"num_result_ids": 4 // optional, if specified fetch this number of results in total but only num_images with metadata
}
```
text, image and image_url are mutually exclusive
and returns:
```js
[
{
"image": "base 64 of an image",
"text": "some result text",
"id": 543
},
{
"image": "base 64 of an image",
"text": "some result text",
"id": 782
}
]
```
Each object may also contain an url field if the metadata provides it.
The id is the position of the item in the index. It may be used to query metadata with the /metadata endpoint:
```js
{
"indice_name": "example_index",
"ids": [543, 782]
}
```
which returns:
```js
{
"image": "base 64 of an image",
"text": "some result text"
// any other key available in the metadata and specified in columns_to_return cli option
}
```
`num_result_ids` argument of `/knn-service` and `/metadata` can be used together to do large knn queries and then fetch the metadata only when needed. It makes sense to do that as knn search can be very efficient thanks to strong [locality of reference](https://en.wikipedia.org/wiki/Locality_of_reference) of knn IVF index making it fast to do knn with a large K, whereas the current on-disk implementation of metadata (hdf5) does not have that property and hence cannot handle retrieving a large amount of random items fast.
In particular this can be used to implement infinite scroll in a front end.
By default the backend will also expose a front end. That front end will by default hit this backend, however you may need to specify whether this is happening over http or https, in this case use the option `--default_backend` to specify the backend url. `--url_column` allows specifying the name of the column url for the front
### Clip back: Benchmark and monitoring
This backends has a 50ms latency if using memory mapped indices and metadata. Throughput is about 20 query/s. For high throughput, using a grpc server is required as well as a GPU for fast clip inference, turning off memory mapping options can also speed up requests, at the cost of high ram usage.
This backends also exposes a prometheus `/metrics` endpoint as well as an human readable summary at `/metrics-summary`.
This can (optionally) be used to setup a [grafana dashboard](doc_assets/grafana_dashboard.json) for monitoring:
[<img src="https://github.com/rom1504/clip-retrieval/raw/main/doc_assets/clip-back-grafana.png" alt="grafana" width="1200">](https://github.com/rom1504/clip-retrieval/raw/main/doc_assets/clip-back-grafana.png)
It can be seen on this dashboard that the slowest part of any call is fetching the image by its url in case of image url search, taking up to 300ms.
For text queries or image queries, the latency is about 50ms.
Here is an example of output in the metrics summary:
```
Among 20.0 calls to the knn end point with an average latency of 0.1889s per request, the step costs are (in order):
name description calls average proportion
0 download_time Time spent downloading an url 6 0.3215s 170.2%
1 metadata_get_time Time spent retrieving metadata 20 0.0415s 21.9%
2 knn_index_time Time spent doing a knn on the index 20 0.0267s 14.1%
3 image_clip_inference_time Time spent doing a image clip inference 6 0.0206s 10.9%
4 text_clip_inference_time Time spent doing a text clip inference 14 0.0186s 9.8%
5 image_prepro_time Time spent doing the image preprocessing 6 0.0097s 5.2%
6 text_prepro_time Time spent doing the text preprocessing 14 0.0020s 1.0%
```
## clip-front
Clip front is a simple UI that connects to clip back and display the results.
You can use it at [clip-retrieval ui](https://rom1504.github.io/clip-retrieval/)
Or you can run it yourself with:
```
npm install -g clip-retrieval-front
clip-retrieval-front 3005
```
You can also run it with `clip-retrieval front` or back from the python package.
### Development
For development it, go to [front](front) and run `npm install` then `npm start`.
## For development
Either locally, or in [gitpod](https://gitpod.io/#https://github.com/rom1504/clip-retrieval) (do `export PIP_USER=false` there)
Setup a virtualenv:
```
python3 -m venv .env
source .env/bin/activate
pip install -e .
```
to run tests:
```
pip install -r requirements-test.txt
```
then
```
make lint
make test
```
You can use `make black` to reformat the code
`python -m pytest -x -s -v tests -k "test_runner"` to run a specific test
If you want to use the front through the python backend or frontend, run
```
cd front
npm install
npm run build
cd ..
pip install -e .
```
%package help
Summary: Development documents and examples for clip-retrieval
Provides: python3-clip-retrieval-doc
%description help
# clip-retrieval
[](https://pypi.python.org/pypi/clip-retrieval)
[](http://badge.fury.io/js/clip-retrieval-front)
[](https://colab.research.google.com/github/rom1504/clip-retrieval/blob/master/notebook/clip-retrieval-getting-started.ipynb)
[](https://gitpod.io/#https://github.com/rom1504/clip-retrieval)
[](https://discord.gg/eq3cAMZtCC)
Easily compute clip embeddings and build a clip retrieval system with them. 100M text+image embeddings can be processed in 20h using a 3080.
* clip client allows remote querying of backend via python. [clip-client notebook](https://colab.research.google.com/github/rom1504/clip-retrieval/blob/master/notebook/clip-client-query-api.ipynb)
* clip inference allows you to quickly (1500 sample/s on a 3080) compute image and text embeddings
* clip index builds efficient indices out of the embeddings
* clip filter allows you to filter out the data using the clip index
* clip back hosts the indices with a simple flask service
* clip front is a simple ui querying the back. Check it out at [clip-retrieval ui](https://rom1504.github.io/clip-retrieval/)
* clip end2end runs img2dataset, inference, index then back and front to make all of this easier to begin with
End to end this make it possible to build a simple semantic search system.
Interested to learn about semantic search in general ? You can read my [medium post](https://rom1504.medium.com/semantic-search-with-embeddings-index-anything-8fb18556443c) on the topic.
Also see [laion5B](https://laion.ai/laion-5b-a-new-era-of-open-large-scale-multi-modal-datasets/) and [semantic search at billions scale](https://rom1504.medium.com/semantic-search-at-billions-scale-95f21695689a) to read more on how to make this scale to billion of samples.
[<img src="https://github.com/rom1504/clip-retrieval/raw/main/doc_assets/clip-front-pic.png" alt="clip front" width="500">](https://rom1504.github.io/clip-retrieval/)
## Who is using clip retrieval ?
* [cah-prepro](https://github.com/rom1504/cah-prepro) preprocess the 400M image+text crawling at home dataset. clip-retrieval is used to compute 400M clip embeddings and the indices
* [autofaiss](https://github.com/criteo/autofaiss) uses clip-retrieval to display an example of use (see the multimodal notebook example there)
* [afiaka87 openai demo](https://gist.github.com/afiaka87/f662486fc45199fa4394f3456c8246d7#file-dalle_blog_semantic_search-ipynb) shows how to look among the 1M example released by openai for their DALL-E demo
* [antarctic-captions by dzryk](https://github.com/dzryk/antarctic-captions) uses autofaiss and clip inference as a way to generate anchors for the image to text task with great success
## Install
pip install clip-retrieval
If your interest it to run the laion5B index, see [this doc](docs/laion5B_back.md)
## Clip client
`ClipClient` allows remote querying of a clip-retrieval backend via python.
See [`ClipClient` - Getting Started Notebook](/notebook/clip-client-query-api.ipynb) for a jupyter notebook example.
### API Initialization
During initialization you can specify a few parameters:
* `backend_url`: the url of the backend. (required)
* `indice_name`: specify the name of the index you want to use. (required)
* `aesthetic_score`: the aesthetic score as rated by [aesthetic_detector](https://github.com/rom1504/aesthetic_detector). Default is `9`.
* `use_mclip`: whether to use a multi-lingual version of CLIP. Default is `False`.
* `aesthetic_weight`: the weight of the aesthetic score. Default is `0.5`
* `modality`: search over image or text in the index, one of `Multimodal.IMAGE` or `Multimodal.TEXT`. Default is `Multimodal.IMAGE`.
* `num_images`: the number of images to return from the API. Default is `40`.
* `deduplicate`: Whether to deduplicate the result by image embedding. Default is true.
* `use_safety_model`: Whether to remove unsafe images. Default is true.
* `use_violence_detector`: Whether to remove images with violence. Default is true.
For instance, to query the hosted backend for Laion5B with the default parameters:
```python
from clip_retrieval.clip_client import ClipClient, Modality
client = ClipClient(url="https://knn5.laion.ai/knn-service", indice_name="laion5B")
```
### Query by text
You can find captioned images similar to the text you provide.
```python
results = client.query(text="an image of a cat")
results[0]
> {'url': 'https://example.com/kitten.jpg', 'caption': 'an image of a kitten', 'id': 14, 'similarity': 0.2367108941078186}
```
### Query by image
You can also find captioned images similar to the image you provide. Images can be passed via local path or url.
```python
cat_results = client.query(image="cat.jpg")
dog_results = client.query(image="https://example.com/dog.jpg")
```
### Query by embedding
You can also find captioned images similar to a clip embedding you provide.
```python
cat_results = client.query(embedding_input=cat_embedding)
```
### Query a directory of images
To enhance an existing dataset with similar text/image pairs, you can query a directory of images and combine the results.
```python
all_results = [result for result in [client.query(image=image) for image in os.listdir("my-images")]]
with open("search-results.json", "w") as f:
json.dump(all_results, f)
```
### Create a dataset
You can create a dataset using the saved json results and the tool `img2dataset`.
```sh
img2dataset "search-results.json" \
--input_format="json" \
--output_folder="knn_search_dataset" \
--caption_col="caption"
```
## clip end2end
First pick a dataset of image urls and captions ([examples](https://github.com/rom1504/img2dataset/tree/main/examples)) then run:
You may want to run `export CUDA_VISIBLE_DEVICES=` to avoid using your GPU if it doesn't have enough VRAM.
```
wget https://github.com/rom1504/img2dataset/raw/main/tests/test_1000.parquet
clip-retrieval end2end test_1000.parquet /tmp/my_output
```
Then go to [http://localhost:1234](http://localhost:1234) and enjoy searching among your pictures
Use `--run_back False` if you don't want to run the backend
## clip inference
Get some images in an `example_folder`, for example by doing:
```
pip install img2dataset
echo 'https://placekitten.com/200/305' >> myimglist.txt
echo 'https://placekitten.com/200/304' >> myimglist.txt
echo 'https://placekitten.com/200/303' >> myimglist.txt
img2dataset --url_list=myimglist.txt --output_folder=image_folder --thread_count=64 --image_size=256
```
You can also put text files with the same names as the images in that folder, to get the text embeddings.
Then run `clip-retrieval inference --input_dataset image_folder --output_folder embeddings_folder`
Output folder will contain:
* img_emb/
* img_emb_0.npy containing the image embeddings as numpy
* text_emb/
* text_emb_0.npy containing the text embeddings as numpy
* metadata/
* metadata_0.parquet containing the image paths, captions and metadata
This scales to million of samples. At 1400 sample/s of a 3080, 10M samples can be processed in 2h.
### API
clip_inference turn a set of text+image into clip embeddings
* **input_dataset** Path to input dataset. Folder if input_format is files. Bash brace pattern such as "{000..150}.tar" (see https://pypi.org/project/braceexpand/) if webdataset (*required*)
* **output_folder** Folder where the clip embeddings will be saved, as well as metadata (*required*)
* **input_format** files or webdataset (default *files*)
* **cache_path** cache path for webdataset (default *None*)
* **batch_size** Number of items to do the inference on at once (default *256*)
* **num_prepro_workers** Number of processes to do the preprocessing (default *8*)
* **enable_text** Enable text processing (default *True*)
* **enable_image** Enable image processing (default *True*)
* **enable_metadata** Enable metadata processing (default *False*)
* **write_batch_size** Write batch size (default *10**6*)
* **wds_image_key** Key to use for images in webdataset. (default *jpg*)
* **wds_caption_key** Key to use for captions in webdataset. (default *txt*)
* **clip_model** CLIP model to load (default *ViT-B/32*). Specify it as `"open_clip:ViT-B-32-quickgelu"` to use the [open_clip](https://github.com/mlfoundations/open_clip).
* **mclip_model** MCLIP model to load (default *sentence-transformers/clip-ViT-B-32-multilingual-v1*)
* **use_mclip** If False it performs the inference using CLIP; MCLIP otherwise (default *False*)
* **use_jit** uses jit for the clip model (default *True*)
* **distribution_strategy** choose how to distribute the job, see distribution section for details (default *sequential*)
* **wds_number_file_per_input_file** estimation of the number of sample per tar if using wds and not specifying output_partition_count (default *10000*)
* **output_partition_count** number of output partitions (default *None*)
* **wandb_project** wandb project to use (default *clip_retrieval*)
* **enable_wandb** whether to use wandb (default *False*)
* **clip_cache_path** cache path for clip (default *None*)
* **slurm_job_name**, the job name to use in slurm. (default *None*)
* **slurm_partition** (default *None*), the slurm partition to create a job in.
* **slurm_jobs**, the number of jobs to create in slurm. (default *None*)
* **slurm_job_comment**, the job comment to use. (default *None*)
* **slurm_nodelist**, a list of specific nodes to use .(default *None*
* **slurm_exclude**, a list of nodes to exclude when creating jobs. (default *None*)
* **slurm_job_timeout**, if not supplied it will default to 2 weeks. (default *None*)
* **slurm_cache_path**, cache path to use for slurm-related tasks. (default *None*)
* **slurm_verbose_wait=False**, wether to print the status of your slurm job (default *False*)
### Inference Worker
If you wish to have more control over how inference is run, you can create and call workers directly using `clip-retrieval inference.worker`
Example Usage:
```bash
clip-retrieval inference.worker \
--tasks="[0]" \
--input_dataset="input/folder/{000000..000100}.tar" \
--output_folder="example/path" \
--input_format="webdataset" \
--output_partition_count="1"
```
Doing so will invoke a single worker that can be instructed to focus on a specific subset of the `input_dataset`. That worker will sequentially process the `tasks` passed to it. Here, `tasks` is a lists of `partition_id`'s that this worker will be responsible for.
To manually compute the number of tasks, use the following formula: `number_samples / wds_number_file_per_input_file`.
The API is very similar to `clip-retrieval inference` with some minor changes:
* **tasks** A list of integers representing the `partition_id`'s that this worker is responsible for computing. (*required*)
* **input_dataset** Path to input dataset. Folder if input_format is files. Bash brace pattern such as "{000..150}.tar" (see https://pypi.org/project/braceexpand/) if webdataset (*required*)
* **output_folder** Folder where the clip embeddings will be saved, as well as metadata (*required*)
* **output_partition_count** number of output partitions (*required*)
* **input_format** files or webdataset (default *files*)
* **cache_path** cache path for webdataset (default *None*)
* **batch_size** Number of items to do the inference on at once (default *256*)
* **num_prepro_workers** Number of processes to do the preprocessing (default *8*)
* **enable_text** Enable text processing (default *True*)
* **enable_image** Enable image processing (default *True*)
* **enable_metadata** Enable metadata processing (default *False*)
* **wds_image_key** Key to use for images in webdataset. (default *jpg*)
* **wds_caption_key** Key to use for captions in webdataset. (default *txt*)
* **clip_model** CLIP model to load (default *ViT-B/32*). Specify it as `"open_clip:ViT-B-32-quickgelu"` to use the [open_clip](https://github.com/mlfoundations/open_clip).
* **mclip_model** MCLIP model to load (default *sentence-transformers/clip-ViT-B-32-multilingual-v1*)
* **use_mclip** If False it performs the inference using CLIP; MCLIP otherwise (default *False*)
* **use_jit** uses jit for the clip model (default *True*)
* **wandb_project** wandb project to use (default *clip_retrieval*)
* **enable_wandb** whether to use wandb (default *False*)
* **clip_cache_path** cache path for clip (default *None*)
> ***Note***: The worker does not accept the following arguments
> * **write_batch_size** Write batch size (default *10**6*)
> * **distribution_strategy** choose how to distribute the job, see distribution section for details (default *sequential*)
> * **wds_number_file_per_input_file** estimation of the number of sample per tar if using wds and not specifying output_partition_count (default *10000*)
> * **any of the SLURM arguments**
### Loading/writing files on hdfs
- To load a webdataset from a hdfs folder, set --input_dataset "pipe:hdfs dfs -cat path_on_hdfs" in the request without the "hdfs://" prefix.
- To write the output on hdfs, set --output_hdfs_folder to the path on hdfs prefixed by "hdfs://"
Example of hdfs query using webdataset format:
`clip_inference --input_dataset "pipe:hdfs dfs -cat /myfolder/webdataset/{00000..00010}.tar" --output_folder "hdfs://myfolder/embeddings" --input_format webdataset
### Loading/writing files on s3
`clip_inference --input_dataset "pipe:aws s3 cp --quiet s3://myfolder/webdataset/{00000..00010}.tar -" --output_folder "s3://myfolder/embeddings" --input_format webdataset
### Distributed inference
To run this on multiple nodes (and multiple gpus), see tutorial at [docs/distributed_clip_inference.md](docs/distributed_clip_inference.md)
## Clip index
Clip index takes as input the output of clip inference and makes an index out of it using [autofaiss](https://github.com/criteo/autofaiss)
`clip-retrieval index --embeddings_folder embeddings_folder --index_folder index_folder`
* `--max_index_memory_usage "16G"` option allow configuring the amount of ram the index will consume. More ram, better knn recall (Default `4G`).
* `--current_memory_available 24G` allows controlling how much ram is used during the creation process (Default `16G`).
* `--image_subfolder "img_emb"` allows to specify a subfolder for the image embeddings which is concatenated to the `--embeddings_folder` option (Default `img_emb`).
* `--text_subfolder "text_emb"` allows to specify a subfolder for the text embeddings which is concatenated to the `--embeddings_folder` option (Default `text_emb`).
* `--copy_metadata True` makes it possible to choose whether to copy metadata or not at the end of the process (Default `True`).
* `--nb_cores 8` allows controlling the number of threads (Default `None`, which will use all cores).
The output is a folder containing:
* image.index containing a faiss index for images
* text.index containing a faiss index for texts
* metadata folder containing the parquet metadata
Thanks to autofaiss and faiss, this scales to hundred of million of samples in a few hours.
You may want to carefully pick how much memory to use for your index in order to maximize the knn recall.
[autofaiss index selection colab](https://colab.research.google.com/github/criteo/autofaiss/blob/master/docs/notebooks/autofaiss_index_selection_demo.ipynb) can help along with `autofaiss score_index` command to check the recall of your index. In general indices using more memory get a better recall and hence are closer to a naive (slow) knn
## Clip filter
Once the embeddings are computed, you may want to filter out the data by a specific query.
For that you can run `clip-retrieval filter --query "cat" --output_folder "cat/" --indice_folder "indice_folder"`
It will copy the 100 best images for this query in the output folder.
Using the `--num_results` or `--threshold` may be helpful to refine the filter
Thanks to fast knn index, this can run in real time (<10ms) for large K values (100000), and in minutes for very large K values.
This scripts works for small datasets. For larger ones, please check [notebook/simple_filter.ipynb].
## Clip back
Clip back is a simple knn service backend. If using both hdf5 and faiss memory mapping, it uses only the memory used by clip which is 4GB.
Run (output_folder is the output of clip index)
```bash
echo '{"example_index": "output_folder"}' > indices_paths.json
clip-retrieval back --port 1234 --indices-paths indices_paths.json
```
Options:
* `--use_jit True` uses jit for the clip model
* `--clip_model "ViT-B/32"` allows choosing the clip model to use. Prefix with `"open_clip:"` to use an [open_clip](https://github.com/mlfoundations/open_clip) model.
* `--enable_mclip_option True` loads the mclip model, making it possible to search in any language.
* `--columns_to_return='["url", "image_path", "caption", "NSFW"]` allows you to specify which columns should be fetched from the metadata and returned by the backend. It's useful to specify less in case of hdf5 caching to speed up the queries.
* `--enable_faiss_memory_mapping=True` option can be passed to use an index with memory mapping.
That decreases the memory usage to zero.
* `--enable_hdf5 True` option can be passed to enable hdf5 caching for the metadata.
HDF5 caching makes it possible to use the metadata with almost no memory usage.
* `--use_arrow True` allows using arrow instead of hdf5. Should be used along with [clip_back_prepro](clip_back_prepro) for very large datasets (billions)
* `--reorder_metadata_by_ivf_index True` option takes advantage of the data locality property of results of a knn ivf indices: it orders the metadata collection in order of the IVF clusters. That makes it possible to have much faster metadata retrieval as the reads are then accessing a few mostly sequential parts of the metadata instead of many non sequential parts. In practice that means being able to retrieve 1M items in 1s whereas only 1000 items can be retrieved in 1s without this method. This will order the metadata using the first image index.
* `--provide_safety_model True` will automatically download and load a [safety model](https://github.com/LAION-AI/CLIP-based-NSFW-Detector). You need to `pip install autokeras` optional dependency for this to work.
* `--provide_violence_detector True` will load a [violence detector](https://github.com/ml-research/OffImgDetectionCLIP), [paper](https://arxiv.org/abs/2202.06675.pdf)
* `--provide_aesthetic_embeddings True` will load the [aesthetic embeddings](https://github.com/LAION-AI/aesthetic-predictor) and allow users to make the query move towards a nicer point of the clip space
These options can also be provided in the config file to have different options for each index. Example:
```json
{
"laion5B": {
"indice_folder": "/mnt/laion5B/prepared_data",
"provide_safety_model": true,
"enable_faiss_memory_mapping": true,
"use_arrow": true,
"enable_hdf5": false,
"reorder_metadata_by_ivf_index": false,
"columns_to_return": ["url", "caption"],
"clip_model": "ViT-L/14",
"enable_mclip_option": false
},
"laion_400m": {
"indice_folder": "/mnt/laion400M/index100",
"provide_safety_model": true,
"enable_faiss_memory_mapping": true,
"enable_hdf5": true,
"use_arrow": false,
"reorder_metadata_by_ivf_index": true,
"enable_mclip_option": true,
"clip_model": "ViT-B/32"
}
}
```
hdf5 or arrow caching is a good idea to use if:
* you do not have enough ram to load the metadata in memory
* your disk is fast (ie you have a ssd)
At this point you have a simple flask server running on port 1234 and that can answer these queries:
* `/indices-list` -> return a list of indices
* `/knn-service` that takes as input:
```js
{
"text": "a text query",
"image": "a base64 image",
"image_url": "http://some-url.com/a.jpg",
"modality": "image", // image or text index to use
"num_images": 4, // number of output images
"indice_name": "example_index",
"num_result_ids": 4 // optional, if specified fetch this number of results in total but only num_images with metadata
}
```
text, image and image_url are mutually exclusive
and returns:
```js
[
{
"image": "base 64 of an image",
"text": "some result text",
"id": 543
},
{
"image": "base 64 of an image",
"text": "some result text",
"id": 782
}
]
```
Each object may also contain an url field if the metadata provides it.
The id is the position of the item in the index. It may be used to query metadata with the /metadata endpoint:
```js
{
"indice_name": "example_index",
"ids": [543, 782]
}
```
which returns:
```js
{
"image": "base 64 of an image",
"text": "some result text"
// any other key available in the metadata and specified in columns_to_return cli option
}
```
`num_result_ids` argument of `/knn-service` and `/metadata` can be used together to do large knn queries and then fetch the metadata only when needed. It makes sense to do that as knn search can be very efficient thanks to strong [locality of reference](https://en.wikipedia.org/wiki/Locality_of_reference) of knn IVF index making it fast to do knn with a large K, whereas the current on-disk implementation of metadata (hdf5) does not have that property and hence cannot handle retrieving a large amount of random items fast.
In particular this can be used to implement infinite scroll in a front end.
By default the backend will also expose a front end. That front end will by default hit this backend, however you may need to specify whether this is happening over http or https, in this case use the option `--default_backend` to specify the backend url. `--url_column` allows specifying the name of the column url for the front
### Clip back: Benchmark and monitoring
This backends has a 50ms latency if using memory mapped indices and metadata. Throughput is about 20 query/s. For high throughput, using a grpc server is required as well as a GPU for fast clip inference, turning off memory mapping options can also speed up requests, at the cost of high ram usage.
This backends also exposes a prometheus `/metrics` endpoint as well as an human readable summary at `/metrics-summary`.
This can (optionally) be used to setup a [grafana dashboard](doc_assets/grafana_dashboard.json) for monitoring:
[<img src="https://github.com/rom1504/clip-retrieval/raw/main/doc_assets/clip-back-grafana.png" alt="grafana" width="1200">](https://github.com/rom1504/clip-retrieval/raw/main/doc_assets/clip-back-grafana.png)
It can be seen on this dashboard that the slowest part of any call is fetching the image by its url in case of image url search, taking up to 300ms.
For text queries or image queries, the latency is about 50ms.
Here is an example of output in the metrics summary:
```
Among 20.0 calls to the knn end point with an average latency of 0.1889s per request, the step costs are (in order):
name description calls average proportion
0 download_time Time spent downloading an url 6 0.3215s 170.2%
1 metadata_get_time Time spent retrieving metadata 20 0.0415s 21.9%
2 knn_index_time Time spent doing a knn on the index 20 0.0267s 14.1%
3 image_clip_inference_time Time spent doing a image clip inference 6 0.0206s 10.9%
4 text_clip_inference_time Time spent doing a text clip inference 14 0.0186s 9.8%
5 image_prepro_time Time spent doing the image preprocessing 6 0.0097s 5.2%
6 text_prepro_time Time spent doing the text preprocessing 14 0.0020s 1.0%
```
## clip-front
Clip front is a simple UI that connects to clip back and display the results.
You can use it at [clip-retrieval ui](https://rom1504.github.io/clip-retrieval/)
Or you can run it yourself with:
```
npm install -g clip-retrieval-front
clip-retrieval-front 3005
```
You can also run it with `clip-retrieval front` or back from the python package.
### Development
For development it, go to [front](front) and run `npm install` then `npm start`.
## For development
Either locally, or in [gitpod](https://gitpod.io/#https://github.com/rom1504/clip-retrieval) (do `export PIP_USER=false` there)
Setup a virtualenv:
```
python3 -m venv .env
source .env/bin/activate
pip install -e .
```
to run tests:
```
pip install -r requirements-test.txt
```
then
```
make lint
make test
```
You can use `make black` to reformat the code
`python -m pytest -x -s -v tests -k "test_runner"` to run a specific test
If you want to use the front through the python backend or frontend, run
```
cd front
npm install
npm run build
cd ..
pip install -e .
```
%prep
%autosetup -n clip-retrieval-2.36.1
%build
%py3_build
%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
find usr/lib -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
find usr/lib64 -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
find usr/bin -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
find usr/sbin -type f -printf "/%h/%f\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
find usr/share/man -type f -printf "/%h/%f.gz\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .
%files -n python3-clip-retrieval -f filelist.lst
%dir %{python3_sitelib}/*
%files help -f doclist.lst
%{_docdir}/*
%changelog
* Fri May 05 2023 Python_Bot <Python_Bot@openeuler.org> - 2.36.1-1
- Package Spec generated
|