Package: cn-clip
中文说明|EnglishModelScope｜Demo｜Paper｜  BlogThis is the Chinese version of CLIP. We use a large-scale Chinese image-text pair dataset (~200M) to train the model, and we hope that it can help users to conveniently achieveimage representation generation,cross-modal retrievalandzero-shot image classificationfor Chinese data. This repo is based onopen_clip project. We have made some optimization for better performance on Chinese data, and we provide the details in the following.News2022.12.12 ImplementFLIPstrategy, which can beactivatedduring finetuning (Thanks@zwkkkforthe PR❤️）2022.12.3 The datasets of the Chinese version of theELEVATERbenchmark are publicly available. SeeNotes for datasetsfor more information.2022.12.1 Chinese-CLIP model & representation generation API are officially merged into Huggingface transformers🤗 codebase.2022.11.22 Releasezero-shot image classificationcode. SupportELEVATERzero-shot classification benchmark.2022.11.3 Release RN50, ViT-H-14 models. Releasetechnical report.2022.9.22 Release ViT-L-14, ViT-L-14-336 models.2022.7.13 Releasefast image & text representation generation API, which facitilates usage of our CLIP models quickly.2022.7.8 Release the project Chinese-CLIP! Releaseimage-text retrievalcode.Models and ResultsModel CardCurrently, we release 5 different sizes of Chinese-CLIP models. Detailed information and download link of each Chinese-CLIP model are provided below:ModelCkpt#Params (All)Backbone (I)#Params (I)Backbone (T)#Params (T)ResolutionCN-CLIPRN50Download77MResNet5038MRBT339M224CN-CLIPViT-B/16Download188MViT-B/1686MRoBERTa-wwm-Base102M224CN-CLIPViT-L/14Download406MViT-L/14304MRoBERTa-wwm-Base102M224CN-CLIPViT-L/14@336pxDownload407MViT-L/14304MRoBERTa-wwm-Base102M336CN-CLIPViT-H/14Download958MViT-H/14632MRoBERTa-wwm-Large326M224ResultsWe conducted zero-shot inference and finetuning experiments onMUGE Retrieval,Flickr30K-CNandCOCO-CNfor the evaluation of cross-modal retrieval, and conducted experiments on 10 image classification datasets of theELEVATERbenchmark for the evaluation of zero-shot image classification. Results are shown below. Due to space limitation, here we only list the performance of the best performing Chinese-CLIP and baseline models. For detailed performance of each Chinese-CLIP model size, please refer toResults.md.MUGE Text-to-Image Retrieval (Official Validation Set):SetupZero-shotFinetuneMetricR@1R@5R@10MRR@1R@5R@10MRWukong42.769.078.063.252.777.985.672.1R2D249.575.783.269.560.182.989.477.5CN-CLIP63.084.189.278.868.988.793.183.6Flickr30K-CN Retrieval (Official Test Set):TaskText-to-ImageImage-to-TextSetupZero-shotFinetuneZero-shotFinetuneMetricR@1R@5R@10R@1R@5R@10R@1R@5R@10R@1R@5R@10Wukong51.778.986.377.494.597.076.194.897.592.799.199.6Taiyi60.885.091.0---------R2D260.986.892.784.496.798.477.696.798.995.699.8100.0CN-CLIP71.291.495.583.896.998.681.697.598.895.399.7100.0COCO-CN Retrieval (Official Test Set):TaskText-to-ImageImage-to-TextSetupZero-shotFinetuneZero-shotFinetuneMetricR@1R@5R@10R@1R@5R@10R@1R@5R@10R@1R@5R@10Wukong53.480.290.174.094.498.155.281.090.673.394.098.0Taiyi60.084.093.3---------R2D256.485.093.179.196.598.963.389.395.779.397.198.7CN-CLIP69.289.996.181.596.999.163.086.692.983.597.399.2Zero-shot Image Classification:TaskCIFAR10CIFAR100DTDEuroSATFERFGVCKITTIMNISTPCVOCGIT88.561.142.943.441.46.722.168.950.080.2ALIGN94.976.866.152.150.825.041.274.055.283.0CLIP94.977.056.063.048.333.311.579.062.384.0Wukong95.477.140.950.3------CN-CLIP96.079.751.252.055.126.249.979.463.584.9Getting StartedInstallation RequirementsTo start with this project, make sure that your environment meets the requirements below:python >= 3.6.4pytorch >= 1.8.0 (with torchvision >= 0.9.0)CUDA Version >= 10.2Run the following command to install required packages.pipinstall-rrequirements.txtAPI Use CaseWe provide a simple code snippet to show how to use the API for Chinese-CLIP. For starters, please install cn_clip:# to install the latest stable releasepipinstallcn_clip# or install from source codecdChinese-CLIP
pipinstall-e.After installation, use Chinese CLIP to compute the image (example) & text embeddings and similarities as shown below:importtorchfromPILimportImageimportcn_clip.clipasclipfromcn_clip.clipimportload_from_name,available_modelsprint("Available models:",available_models())# Available models: ['ViT-B-16', 'ViT-L-14', 'ViT-L-14-336', 'ViT-H-14', 'RN50']device="cuda"iftorch.cuda.is_available()else"cpu"model,preprocess=load_from_name("ViT-B-16",device=device,download_root='./')model.eval()image=preprocess(Image.open("examples/pokemon.jpeg")).unsqueeze(0).to(device)text=clip.tokenize(["杰尼龟","妙蛙种子","小火龙","皮卡丘"]).to(device)withtorch.no_grad():image_features=model.encode_image(image)text_features=model.encode_text(text)# Normalize the features. Please use the normalized features for downstream tasks.image_features/=image_features.norm(dim=-1,keepdim=True)text_features/=text_features.norm(dim=-1,keepdim=True)logits_per_image,logits_per_text=model.get_similarity(image,text)probs=logits_per_image.softmax(dim=-1).cpu().numpy()print("Label probs:",probs)# [[1.268734e-03 5.436878e-02 6.795761e-04 9.436829e-01]]However, if you are not satisfied with only using the API, move on for more details about training and inference.TutorialCurrently, we provide the tutorial ofcross-modal retrievalandzero-shot image classificationbelow.Cross-Modal RetrievalCode OrganizationAfter cloning this project, please create a new directory${DATAPATH}for datasets, checkpoints and logs。A recommended workspace structure is demonstrated below：Chinese-CLIP/
├── run_scripts/
│   ├── muge_finetune_vit-b-16_rbt-base.sh
│   ├── flickr30k_finetune_vit-b-16_rbt-base.sh
│   └── ...           # more scripts for finetuning and evaluation...
└── src/
    ├── clip/
    ├── eval/
    ├── preprocess/
    └── training/

${DATAPATH}
├── pretrained_weights/
├── experiments/
└── datasets/
    ├── MUGE/
    ├── Flickr30k-CN/
    └── .../          # more datasets...PreparationWe provide links for the downloading of pretrained checkpoints, as well as the data preprocessing procedures for finetuning.Pretrained CheckpointsPlease refer tomodel card sectionabove and download the model checkpoint. We recommend putting the checkpoint in${DATAPATH}/pretrained_weights/.Data PreprocessingWe advise to organize the data in the following way to ensure the efficiency of accessing and processing data:${DATAPATH}
└── datasets/
    └── ${dataset_name}/
        ├── train_imgs.tsv      # image id & image content
        ├── train_texts.jsonl   # text id & text content, with list of paired image ids
        ├── valid_imgs.tsv
        ├── valid_texts.jsonl
        ├── test_imgs.tsv
        └── test_texts.jsonlwhere${dataset_name}refers to the name of dataset (e.g., MUGE).To ensure the efficiency of processing data, we did not store images with small files, but instead we encode them to base64 strings and store them in${split}_imgs.tsv. Each line represents an image, where there are id (int) and base64 string, split by\t, as shown below:1000002	/9j/4AAQSkZJ...YQj7314oA//2Q==Transforming image files to base64 strings is simple. Run the following code:fromPILimportImagefromioimportBytesIOimportbase64img=Image.open(file_name)# path to fileimg_buffer=BytesIO()img.save(img_buffer,format=img.format)byte_data=img_buffer.getvalue()base64_str=base64.b64encode(byte_data)# bytesbase64_str=base64_str.decode("utf-8")# strTexts and image-text pairing relations are stored in${split}_texts.jsonl, where each line is a json as shown below:{"text_id": 8428, "text": "高级感托特包斜挎", "image_ids": [1076345, 517602]}For the test set where only the texts are given and the image-text pairing relations are unknown, just leave theimage_idsfield as an empty list,"image_ids": [].Finally, we need to serialize tsv and jsonl and transform them to LMDB files, which is easy for random access during training.python src/preprocess/build_lmdb_dataset.py \
    --data_dir ${DATAPATH}/datasets/${dataset_name}
    --splits train,valid,testFor example, for the MUGE dataset, we name${dataset_name}to MUGE.--splitsrefers to dataset splits，split by commas without space. After that, there will be LMDB files in the directory.${DATAPATH}
└── datasets/
    └── ${dataset_name}/
        └── lmdb/
            ├── train
            │   ├── imgs
            │   └── pairs
            ├── valid
            └── testFor easier use, we have provided preprocessed MUGE (download link) and Flickr30K-CN (download link) datasets in zip format. To use them, just download and unzip it under${DATAPATH}/datasets/.FinetuningWe introduce the procedures of training for users to learn about the details of the model. We finetune with the pretrained Chinese CLIP. For MUGE and Flickr30K-CN, we provide scriptsrun_scripts/muge_finetune_vit-b-16_rbt-base.shandrun_scripts/flickr30k_finetune_vit-b-16_rbt-base.sh.The scripts support single-worker and distributed training. Before running, follow the instructions at the beggining of the scripts and fill in your configuration for distributed training. Then run the scripts to start your training. If the GPU memory is insufficient, you can consider toactivate the gradient checkpointing strategyin the configuration.Logs and checkpoints will be saved at your specified paths.cdChinese-CLIP/
bashrun_scripts/muge_finetune_vit-b-16_rbt-base.sh${DATAPATH}The configuration for training includes:Distributed trainingWORKER_CNT: the number of machines.GPUS_PER_NODE: the number of GPUS on each machine.Data for training/validationtrain-data: directory of training data. Follow the procedures above the create LMDB files.val-data: directory of validation data.num-workers: the number of workers for dataloader.Training hyper-paramsvision-model: specified visual backbones. Select from["ViT-B-16", "ViT-L-14", "ViT-L-14-336", "ViT-H-14", "RN50"].text-model: specified language backbones. Select from["RoBERTa-wwm-ext-base-chinese", "RoBERTa-wwm-ext-large-chinese", "RBT3-chinese"].context-length: sequence length for text inputs.warmup: steps for warmup.batch-size: batch size for a worker (make sure that the number of training samples larger thanbatch-size * GPUs).lr: learning rate.wd: weight decay.max-steps: training steps. Also you can setmax-epochsto set the number of training epochs.freeze-vision: whether to freeze the visual backbone.use-augment: whether to useAutoAugmentfor data augmentation.valid-batch-size: validation batch size for a worker (make sure that the number of validation samples larger thanvalid-batch-size * GPUs).valid-step-intervalandvalid-epoch-interval: validation step / epoch frequency, if set to -1 then validation will be disabled during finetuning.grad-checkpointing:usegradient checkpointingwhich does not keep the activations during forward computation, this strategy trades more computation and iteration time for less GPU memory cost. (store_trueargument, just add--grad-checkpointingin the script to activate it, requires Pytorch>1.8.0)mask-ratio:useFLIPstrategy which randomly masks a ratio of image patches to save GPU memory and speed up training. Default to 0.0, which disables the strategy.Ouputsname: specified output path. Hyperparameter logs, training logs, and checkpoints will be saved at${DATAPATH}/experiments/${name}/.save-step-frequencyandsave-epoch-frequency: the intervals for saving checkpoints.report-training-batch-acc: whether to report the in-batch image-to-text and text-to-image retrieval accuracy.Checkpointsresume: the checkpoint path for weights to restore. In the provided example script, the path refers to the pretrained checkpoint path. Users can change to your own checkpoint path.reset-data-offset: whether to restore training at the data breakpoint.reset-optimizer: whether to restore the optimizer state。After training, the log will be saved at${DATAPATH}/experiments/${name}/out_${timestamp}.log. Example of log is shown below:2022-12-11,20:40:34 | INFO | Rank 0 | Global Steps: 1/735 | Train Epoch: 1 [1024/250880 (0%)] | Loss: 2.371020 | Image2Text Acc: 49.90 | Text2Image Acc: 48.73 | Data Time: 1.039s | Batch Time: 3.625s | LR: 0.000000 | logit_scale: 4.605 | Global Batch Size: 1024The example of validation log is shown below:2022-12-11,20:42:47 | INFO | Rank 0 | Validation Result (epoch 1 @ 150 steps) | Valid Loss: 0.502810 | Image2Text Acc: 84.95 | Text2Image Acc: 84.26 | logit_scale: 4.605 | Valid Batch Size: 128Attention: The convergence and stability of contrastive learning is highly relevant to the total batch size. If you use a smaller batch size, (in comparison with the default 128 per-GPU * 8 GPU), we advise you to use a smaller learning rat. We recommend using more GPUs and larger batch size for better performance.Inference and EvaluationWe provide procedures for representation generation and cross-modal retrieval, as demonstrated below:Image/Text Representation GenerationBy now the code supports representation generation with a single worker. Follow the commands below:cdChinese-CLIP/exportCUDA_VISIBLE_DEVICES=0exportPYTHONPATH=${PYTHONPATH}:`pwd`/srcsplit=valid# validation / test setresume=${DATAPATH}/pretrained_weights/clip_cn_vit-b-16.pt

python-usrc/eval/extract_features.py\--extract-image-feats\--extract-text-feats\--image-data="${DATAPATH}/datasets/${dataset_name}/lmdb/${split}/imgs"\--text-data="${DATAPATH}/datasets/${dataset_name}/${split}_texts.jsonl"\--img-batch-size=32\--text-batch-size=32\--context-length=52\--resume=${resume}\--vision-model=ViT-B-16\--text-model=RoBERTa-wwm-ext-base-chineseBy default, the representations are stored at${DATAPATH}/datasets/${dataset_name}. Specifically, the image representations are stored at${split}_imgs.img_feat.jsonl. Each line stores a json of image representation, as shown below:{"image_id": 1000002, "feature": [0.0198, ..., -0.017, 0.0248]}Text representations are stored at${split}_texts.txt_feat.jsonl，as shown below:{"text_id": 248816, "feature": [0.1314, ..., 0.0018, -0.0002]}KNN RetrievalFor small-scale retrieval datasets, we provide a simple implementation of KNN retrieval, to facilitate the retrieval of top-k results in cross-modal retrieval. (tips: If you want to build aretrieval demoin your project like us, we suggest first to use Chinese-CLIP to compute image and text embeddings, and then employ an opensource servering frameworkclip-retrievalto deploy the front-end and back-end servering.)For text-to-image retrieval, run the commands below:cdChinese-CLIP/split=valid# validation / test splitspython-usrc/eval/make_topk_predictions.py\--image-feats="${DATAPATH}/datasets/${dataset_name}/${split}_imgs.img_feat.jsonl"\--text-feats="${DATAPATH}/datasets/${dataset_name}/${split}_texts.txt_feat.jsonl"\--top-k=10\--eval-batch-size=32768\--output="${DATAPATH}/datasets/${dataset_name}/${split}_predictions.jsonl"Results are stored at specified jsonl files. Each line consists of top-k image ids for a text query, as shown below:{"text_id":153915,"image_ids":[5791244,1009692167,7454547004,3564007203,38130571,2525270674,2195419145,2503091968,4966265765,3690431163]}For image-to-text retrieval, run the commands below：split=valid# validation / test splitspython-usrc/eval/make_topk_predictions_tr.py\--image-feats="${DATAPATH}/datasets/${dataset_name}/${split}_imgs.img_feat.jsonl"\--text-feats="${DATAPATH}/datasets/${dataset_name}/${split}_texts.txt_feat.jsonl"\--top-k=10\--eval-batch-size=32768\--output="${DATAPATH}/datasets/${dataset_name}/${split}_tr_predictions.jsonl"Results are stored at specified jsonl files. Each line consists of top-k text ids for an image query, as shown below:{"image_id":977856234,"text_ids":[156914,157914,158914,155914,156179,158907,157179,154179,154914,154723]}Recall MetricWe provide scripts for computing the Recall@1/5/10 and mean recall (the mean of Recall@1/5/10). Run the commands to get the scores:For text-to-image retrieval, run the commands below:split=valid# validation / test splitspythonsrc/eval/evaluation.py\${DATAPATH}/datasets/${dataset_name}/${split}_texts.jsonl\${DATAPATH}/datasets/${dataset_name}/${split}_predictions.jsonl\output.json
catoutput.jsonFor image-to-text retrieval, run the commands first to transform text-to-image jsonls to image-to-text ones:pythonsrc/eval/transform_ir_annotation_to_tr.py\--input${DATAPATH}/datasets/${dataset_name}/${split}_texts.jsonlAfter that，run the following commandssplit=valid# validation / test splitspythonsrc/eval/evaluation_tr.py\${DATAPATH}/datasets/${dataset_name}/${split}_texts.tr.jsonl\${DATAPATH}/datasets/${dataset_name}/${split}_tr_predictions.jsonl\output.json
catoutput.jsonThe printed results are shown below:{"success":true,"score":85.67,"scoreJson":{"score":85.67,"mean_recall":85.67,"r1":71.2,"r5":90.5,"r10":95.3}}Zero-shot Image ClassificationThis section introduces the use of Chinese-CLIP for zero-shot image classification. We use the experiment on a dataset of the benchmark ELEVATER as an example. ELEVATER is a benchmark consist of several widely used classification datasets and evaluates the zero-shot performance on these datasets, including CIFAR-10, CIFAR-100, MNIST, etc. In our experiments, we have perpared Chinese prompts and label names with the original images for each ELEVATER dataset (refer toNotes for datasetsfor download) to evaluate Chinese-CLIP. For more information about ELEVATER, please clickthis link. Users can also follow the procedure below to prepare and evaluate their own classification datasets.PreparationWe need to prepare only the test set and the pretrained Chinese-CLIP checkpoint. It's recommended to prepare these directories under a user defined${DATAPATH}and organize them as follows:${DATAPATH}
├── pretrained_weights/
└── datasets/
    └── ${dataset_name}/
        ├── label_cn.txt
        └── test/
	    ├── 000/ # label id，fill 0 by the left to 3 digits so that the labels can be alphabetically ordered
	    │   ├── image_0003.jpg # image sample, no specific requirements for the naming
	    │   ├── image_0005.jpg
	    │   └── ...
	    ├── 001/
	    │   ├── image_0001.jpg
	    │   ├── image_0002.jpg
	    │   └── ...
	    └── 002/
	        ├── image_0003.jpg
	        ├── image_0005.jpg
	        └── ...
	    ...Make sure the data are categorized by their label id, and make sure the ids are alphabetically orderd (for numbers larger than 10, uselabel.zfill(3)to fill 0 by the left to 3 digits, like 001，002, etc).label_cn.txtrefers to the file of label names. Each line has a label name, as demonstrated below:accordion
airplane
anchor
...The label id is[line number]-1. For example, the label id for the first line is 0, and the one for the second line is 1. If the number of labels is larger than 10, all labels are filled with 0 by the left to 3-digit numbers. For example, if the number of labels is 100, the ids are000-099. Users should create a directory for each label, and put the corresponding samples into the directories. We provide the processed dataset CIFAR-100 as an example, and please clickthis linkto download the prepared dataset. To evaluate other datasets of ELEVATER, please refer toNotes for datasetsfor download.Prediction and EvaluationWe provide a script for prediction and evaluation. Please checkrun_scripts/zeroshot_eval.shfor more details. An example command is shown below:bashrun_scripts/zeroshot_eval.sh0\${DATAPATH}${dataset_name}\${vision_model}${text_model}\${ckpt_path}${index_file}where the arguments stand for:the first argument0refers to the GPU IDDATAPATHrefers to the root directory storing the checkpoint and dataset, as mentioned in Preparation part abovedataset_namerefers to the directory name of the dataset, e.g. cifar-100, as mentioned in Preparation part abovevision_modelrefers to the type of vision encoder, including["ViT-B-32", "ViT-B-16", "ViT-L-14", "ViT-L-14-336", "RN50", "ViT-H-14"]text_modelrefers to the type of text encoder, including["RoBERTa-wwm-ext-base-chinese", "RoBERTa-wwm-ext-large-chinese", "RBT3-chinese"]ckpt_pathrefers to the complete path of the pretrained Chinese-CLIP checkpointindex_fileis optional and only needed when you would like to submit to ELEVATER official website. Please refer toNotes for datasetsfor more detailsFor example, to evaluate ViT-B/16 on CIFAR-100, please run (the${DATAPATH}should be replaced with your real path):bashrun_scripts/zeroshot_eval.sh0\${DATAPATH}cifar-100\ViT-B-16RoBERTa-wwm-ext-base-chinese\${DATAPATH}/pretrained_weights/clip_cn_vit-b-16.ptTop-1 accuracy will be printed.Result:
zeroshot-top1: 0.6444On CIFAR-100, the ViT-B/16 model of Chinese-CLIP will achieve the accuracy of 64.4%. For the zero-shot evaluation results of other model scales and other datasets, please refer toResults.md.Also, a json file will be saved, which serves the submission of ELEVATER. An example of the json file is shown below：{"model_name":"CN-CLIP-ViT-B-16","dataset_name":"cifar-100","num_trainable_params":0,"num_params":188262913,"num_visual_params":86192640,"num_backbone_params":188262913,"n_shot":0,"rnd_seeds":[123],"predictions":"prediction probability tensor [size: (1, 10000, 100)]"}It includes meta data like the name of modelmodel_name, the dataset namedataset_name, the number of parametersnum_params, the number of parameters of vision encodernum_visual_params, and also the outputs of the model, namely the predicted probability tensor, whose size is[1, num_samples, num_labels].Zero-Shot Classification Online DemoBased on the representation generation API which we have integrated into Huggingface transformers, we are able to provide online demos of zero-shot classification task on Huggingface Model Hub🤗 for each scale of Chinese-CLIP model. The links are given below:OFA-Sys/chinese-clip-vit-base-patch16OFA-Sys/chinese-clip-vit-large-patch14OFA-Sys/chinese-clip-vit-large-patch14-336pxOFA-Sys/chinese-clip-vit-huge-patch14（Update on 12.10🔥）New version of demo deployed on Huggingface Spaces: the 4 model scales above are all gathered into the same demo page, supporting customed prompt template by user.Welcome to try!CitationIf you find the project helpful, please star this project and cite the related articles. Thanks for your support!@article{chinese-clip,
  title={Chinese CLIP: Contrastive Vision-Language Pretraining in Chinese},
  author={Yang, An and Pan, Junshu and Lin, Junyang and Men, Rui and Zhang, Yichang and Zhou, Jingren and Zhou, Chang},
  journal={arXiv preprint arXiv:2211.01335},
  year={2022}
}