Package: clip-retrieval
clip-retrievalEasily 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 notebookclip inference allows you to quickly (1500 sample/s on a 3080) compute image and text embeddingsclip index builds efficient indices out of the embeddingsclip filter allows you to filter out the data using the clip indexclip back hosts the indices with a simple flask serviceclip front is a simple ui querying the back. Check it out atclip-retrieval uiclip end2end runs img2dataset, inference, index then back and front to make all of this easier to begin withEnd to end this make it possible to build a simple semantic search system.
Interested to learn about semantic search in general ? You can read mymedium poston the topic.Also seelaion5Bandsemantic search at billions scaleto read more on how to make this scale to billion of samples.If you believe in making reusable tools to make data easy to use for ML and you would like to contribute, please join theDataToMLchat.Related projectsall_clipto load any clip modelimg2datasetto download images from urlsopen_clipto train clip modelsCLIP_benchmarkto evaluate clip modelsWho is using clip retrieval ?cah-prepropreprocess the 400M image+text crawling at home dataset. clip-retrieval is used to compute 400M clip embeddings and the indicesautofaissuses clip-retrieval to display an example of use (see the multimodal notebook example there)afiaka87 openai demoshows how to look among the 1M example released by openai for their DALL-E demoantarctic-captions by dzrykuses autofaiss and clip inference as a way to generate anchors for the image to text task with great successInstallpip install clip-retrievalIf your interest it to run the laion5B index, seethis docClip clientClipClientallows remote querying of a clip-retrieval backend via python.SeeClipClient- Getting Started Notebookfor a jupyter notebook example.API InitializationDuring 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 byaesthetic-predictor. Default is9.use_mclip: whether to use a multi-lingual version of CLIP. Default isFalse.aesthetic_weight: the weight of the aesthetic score. Default is0.5modality: search over image or text in the index, one ofMultimodal.IMAGEorMultimodal.TEXT. Default isMultimodal.IMAGE.num_images: the number of images to return from the API. Default is40.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:fromclip_retrieval.clip_clientimportClipClient,Modalityclient=ClipClient(url="https://knn.laion.ai/knn-service",indice_name="laion5B-L-14")Query by textYou can find captioned images similar to the text you provide.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 imageYou can also find captioned images similar to the image you provide.  Images can be passed via local path or url.cat_results=client.query(image="cat.jpg")dog_results=client.query(image="https://example.com/dog.jpg")Query by embeddingYou can also find captioned images similar to a clip embedding you provide.cat_results=client.query(embedding_input=cat_embedding)Query a directory of imagesTo enhance an existing dataset with similar text/image pairs, you can query a directory of images and combine the results.all_results=[resultforresultin[client.query(image=image)forimageinos.listdir("my-images")]]withopen("search-results.json","w")asf:json.dump(all_results,f)Create a datasetYou can create a dataset using the saved json results and the toolimg2dataset.img2dataset"search-results.json"\--input_format="json"\--output_folder="knn_search_dataset"\--caption_col="caption"clip end2endFirst pick a dataset of image urls and captions (examples) then run:You may want to runexport 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_files/test_1000.parquet
clip-retrieval end2end test_1000.parquet /tmp/my_outputThen go tohttp://localhost:1234and enjoy searching among your picturesUse--run_back Falseif you don't want to run the backendclip inferenceGet some images in anexample_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=256You can also put text files with the same names as the images in that folder, to get the text embeddings.Then runclip-retrieval inference --input_dataset image_folder --output_folder embeddings_folderOutput folder will contain:img_emb/img_emb_0.npy containing the image embeddings as numpytext_emb/text_emb_0.npy containing the text embeddings as numpymetadata/metadata_0.parquet containing the image paths, captions and metadataThis scales to million of samples. At 1400 sample/s of a 3080, 10M samples can be processed in 2h.APIclip_inference turn a set of text+image into clip embeddingsinput_datasetPath to input dataset. Folder if input_format is files. Bash brace pattern such as "{000..150}.tar" (seehttps://pypi.org/project/braceexpand/) if webdataset (required)output_folderFolder where the clip embeddings will be saved, as well as metadata (required)input_formatfiles or webdataset (defaultfiles)cache_pathcache path for webdataset (defaultNone)batch_sizeNumber of items to do the inference on at once (default256)num_prepro_workersNumber of processes to do the preprocessing (default8)enable_textEnable text processing (defaultTrue)enable_imageEnable image processing (defaultTrue)enable_metadataEnable metadata processing (defaultFalse)write_batch_sizeWrite batch size (default10**6)wds_image_keyKey to use for images in webdataset. (defaultjpg)wds_caption_keyKey to use for captions in webdataset. (defaulttxt)clip_modelCLIP model to load (defaultViT-B/32). Specify it as"open_clip:ViT-B-32/laion2b_s34b_b79k"to use theopen_clipor"hf_clip:patrickjohncyh/fashion-clip"to use thehugging faceclip model.mclip_modelMCLIP model to load (defaultsentence-transformers/clip-ViT-B-32-multilingual-v1)use_mclipIf False it performs the inference using CLIP; MCLIP otherwise (defaultFalse)use_jituses jit for the clip model (defaultTrue)distribution_strategychoose how to distribute the job, see distribution section for details (defaultsequential)wds_number_file_per_input_fileestimation of the number of sample per tar if using wds and not specifying output_partition_count (default10000)output_partition_countnumber of output partitions (defaultNone)wandb_projectwandb project to use (defaultclip_retrieval)enable_wandbwhether to use wandb (defaultFalse)clip_cache_pathcache path for clip (defaultNone)slurm_job_name, the job name to use in slurm. (defaultNone)slurm_partition(defaultNone), the slurm partition to create a job in.slurm_jobs, the number of jobs to create in slurm. (defaultNone)slurm_job_comment, the job comment to use. (defaultNone)slurm_nodelist, a list of specific nodes to use .(defaultNone)slurm_exclude, a list of nodes to exclude when creating jobs. (defaultNone)slurm_job_timeout, if not supplied it will default to 2 weeks. (defaultNone)slurm_cache_path, cache path to use for slurm-related tasks. (defaultNone)slurm_verbose_wait=False, wether to print the status of your slurm job (defaultFalse)DeepSparse BackendDeepSparseis an inference runtime for fast sparse model inference on CPUs. There is a backend available within clip-retrieval by installing it withpip install deepsparse-nightly[clip], and specifying aclip_modelwith a prepended"nm:", such as"nm:neuralmagic/CLIP-ViT-B-32-256x256-DataComp-s34B-b86K-quant-ds"or"nm:mgoin/CLIP-ViT-B-32-laion2b_s34b_b79k-ds".Inference WorkerIf you wish to have more control over how inference is run, you can create and call workers directly usingclip-retrieval inference.workerExample Usage:clip-retrievalinference.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 theinput_dataset. That worker will sequentially process thetaskspassed to it. Here,tasksis a lists ofpartition_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 toclip-retrieval inferencewith some minor changes:tasksA list of integers representing thepartition_id's that this worker is responsible for computing. (required)input_datasetPath to input dataset. Folder if input_format is files. Bash brace pattern such as "{000..150}.tar" (seehttps://pypi.org/project/braceexpand/) if webdataset (required)output_folderFolder where the clip embeddings will be saved, as well as metadata (required)output_partition_countnumber of output partitions (required)input_formatfiles or webdataset (defaultfiles)cache_pathcache path for webdataset (defaultNone)batch_sizeNumber of items to do the inference on at once (default256)num_prepro_workersNumber of processes to do the preprocessing (default8)enable_textEnable text processing (defaultTrue)enable_imageEnable image processing (defaultTrue)enable_metadataEnable metadata processing (defaultFalse)wds_image_keyKey to use for images in webdataset. (defaultjpg)wds_caption_keyKey to use for captions in webdataset. (defaulttxt)clip_modelCLIP model to load (defaultViT-B/32). Specify it as"open_clip:ViT-B-32-quickgelu"to use theopen_clipor"hf_clip:patrickjohncyh/fashion-clip"to use thehugging faceclip model.mclip_modelMCLIP model to load (defaultsentence-transformers/clip-ViT-B-32-multilingual-v1)use_mclipIf False it performs the inference using CLIP; MCLIP otherwise (defaultFalse)use_jituses jit for the clip model (defaultTrue)wandb_projectwandb project to use (defaultclip_retrieval)enable_wandbwhether to use wandb (defaultFalse)clip_cache_pathcache path for clip (defaultNone)Note: The worker does not accept the following argumentswrite_batch_sizeWrite batch size (default10**6)distribution_strategychoose how to distribute the job, see distribution section for details (defaultsequential)wds_number_file_per_input_fileestimation of the number of sample per tar if using wds and not specifying output_partition_count (default10000)any of the SLURM argumentsLoading/writing files on hdfsTo 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 webdatasetLoading/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 webdatasetDistributed inferenceTo run this on multiple nodes (and multiple gpus), see tutorial atdocs/distributed_clip_inference.mdClip indexClip index takes as input the output of clip inference and makes an index out of it usingautofaissclip-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 (Default4G).--current_memory_available 24Gallows controlling how much ram is used during the creation process (Default16G).--image_subfolder "img_emb"allows to specify a subfolder for the image embeddings which is concatenated to the--embeddings_folderoption (Defaultimg_emb).--text_subfolder "text_emb"allows to specify a subfolder for the text embeddings which is concatenated to the--embeddings_folderoption (Defaulttext_emb).--copy_metadata Truemakes it possible to choose whether to copy metadata or not at the end of the process (DefaultTrue).--nb_cores 8allows controlling the number of threads (DefaultNone, which will use all cores).The output is a folder containing:image.index containing a faiss index for imagestext.index containing a faiss index for textsmetadata folder containing the parquet metadataThanks 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 colabcan help along withautofaiss score_indexcommand 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) knnClip filterOnce the embeddings are computed, you may want to filter out the data by a specific query.
For that you can runclip-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_resultsor--thresholdmay be helpful to refine the filterThanks 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 backClip 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)echo'{"example_index": "output_folder"}'>indices_paths.json
clip-retrievalback--port1234--indices-pathsindices_paths.jsonOptions:--use_jit Trueuses jit for the clip model--clip_model "ViT-B/32"allows choosing the clip model to use. Prefix with"open_clip:"to use anopen_clipmodel.--enable_mclip_option Trueloads 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=Trueoption can be passed to use an index with memory mapping.
That decreases the memory usage to zero.--enable_hdf5 Trueoption 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 Trueallows using arrow instead of hdf5. Should be used along withclip_back_preprofor very large datasets (billions)--reorder_metadata_by_ivf_index Trueoption 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 Truewill automatically download and load asafety model. You need topip install autokerasoptional dependency for this to work.--provide_violence_detector Truewill load aviolence detector,paper--provide_aesthetic_embeddings Truewill load theaesthetic embeddingsand allow users to make the query move towards a nicer point of the clip spaceThese options can also be provided in the config file to have different options for each index. Example:{"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 memoryyour 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-servicethat takes as input:{"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:[{"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:{"indice_name":"example_index","ids":[543,782]}which returns:{"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_idsargument of/knn-serviceand/metadatacan 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 stronglocality of referenceof 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_backendto specify the backend url.--url_columnallows specifying the name of the column url for the frontClip back: Benchmark and monitoringThis 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/metricsendpoint as well as an human readable summary at/metrics-summary.
This can (optionally) be used to setup agrafana dashboardfor monitoring: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-frontClip front is a simple UI that connects to clip back and display the results.
You can use it atclip-retrieval uiOr you can run it yourself with:npm install -g clip-retrieval-front
clip-retrieval-front 3005You can also run it withclip-retrieval frontor back from the python package.DevelopmentFor development it, go tofrontand runnpm installthennpm start.For developmentEither locally, or ingitpod(doexport PIP_USER=falsethere)Setup a virtualenv:python3 -m venv .env
source .env/bin/activate
pip install -e .to run tests:pip install -r requirements-test.txtthenmake lint
make testYou can usemake blackto reformat the codepython -m pytest -x -s -v tests -k "test_runner"to run a specific testIf you want to use the front through the python backend or frontend, runcd front
npm install
npm run build
cd ..
pip install -e .Citation@misc{beaumont-2022-clip-retrieval,
  author = {Romain Beaumont},
  title = {Clip Retrieval: Easily compute clip embeddings and build a clip retrieval system with them},
  year = {2022},
  publisher = {GitHub},
  journal = {GitHub repository},
  howpublished = {\url{https://github.com/rom1504/clip-retrieval}}
}