Chinese-CLIP Documentation

repository·master·Indexed 27 days ago

https://github.com/ofa-sys/chinese-clip

A specialized version of the CLIP model optimized for Chinese language tasks, including cross-modal retrieval, zero-shot classification, and image-text feature extraction. It provides five model scales (RN50, ViT-B/16, ViT-L/14, ViT-L/14@336px, and ViT-H/14) and supports the cn_clip API for similarity calculations, feature extraction, and fine-tuning via distributed training.

Tokens
17.5K
Snippets
44
Records
72
Agent score
87%

What's inside Chinese-CLIP

  1. Overview of Chinese-CLIP

    master

    Chinese-CLIP is a Chinese version of CLIP trained on a large-scale Chinese image-text pair dataset (~200M). It is designed to facilitate the following tasks for Chinese data:

    • Image representation generation: Extracting features from images.
    • Cross-modal retrieval: Searching for images using text or vice versa.
    • Zero-shot image classification: Classifying images into categories without specific training for those categories.

    The project is based on the open_clip project and includes optimizations for better performance on Chinese data.

  2. Install Chinese-CLIP requirements

    master

    Before using Chinese-CLIP, ensure your environment meets the following requirements:

    • python >= 3.6.4
    • pytorch >= 1.8.0 (with torchvision >= 0.9.0)
    • CUDA Version >= 10.2

    You can install the necessary third-party libraries using the provided requirements.txt file.

    pip install -r requirements.txt
  3. Prepare environment for Chinese-CLIP ONNX & TensorRT deployment

    master

    To deploy Chinese-CLIP models using ONNX or TensorRT for improved inference speed, ensure your hardware and software meet the following requirements:

    • GPU: NVIDIA GPUs with Volta architecture or above (supporting FP16 Tensor Cores). Example: T4 GPU.
    • CUDA: Version 11.6 or higher recommended.
    • CUDNN: Version 8.6.0 or higher recommended. Ensure compatibility with your TensorRT version (e.g., TensorRT 8.5.x requires CUDNN 8.6.0).
    • ONNX: Required for the Pytorch → ONNX → TensorRT conversion pipeline. Recommended versions: onnx==1.13.0, onnxruntime-gpu==1.13.1, and onnxmltools==1.11.1.
    • TensorRT: Version 8.5.x is recommended (e.g., 8.5.2.2).
    • PyTorch: Version 1.12.1 or higher recommended. It is advised to install via pip with the specific CUDA version (e.g., 1.12.1+cu116) rather than using conda to install cudatoolkit to avoid CUDNN version conflicts with TensorRT.
    pip install tensorrt==8.5.2.2 onnx==1.13.0 onnxruntime-gpu==1.13.1 onnxmltools==1.11.1
    pip install torch==1.12.1+cu116 torchvision==0.13.1+cu116 torchaudio==0.12.1 -f https://download.pytorch.org/whl/torch_stable.html
    pip install -r requirements.txt
  4. Download Zero-shot Image Classification Datasets

    master

    The project provides organized versions of 20 datasets (including Caltech-101, CIFAR-10, CIFAR-100, and MNIST) from the ELEVATER Benchmark for direct use with Chinese-CLIP. You can download the complete collection as a single zip file.

    Download Link: https://huggingface.co/datasets/OFA-Sys/chinese-clip-eval/resolve/main/ELEVATER_all.zip (37GB)

  5. Enable knowledge distillation in Chinese-CLIP fine-tuning

    master

    You can improve the image retrieval capabilities of smaller Chinese-CLIP models by distilling knowledge from larger teacher models provided by ModelScope. To enable this during fine-tuning, add the following configuration flags to your fine-tuning shell script:

    • --distillation: Set this flag to enable knowledge distillation on the image side.
    • --teacher-model-name: Specify the name of the teacher model from ModelScope.
    • --kd_loss_weight (optional): The weight for the distillation loss. The default value is 0.5.
  6. Extract features using ONNX or TensorRT

    master

    For downstream tasks like MUGI image-text retrieval, you can use optimized feature extraction scripts for ONNX and TensorRT. These scripts are designed to be drop-in replacements for the standard Pytorch extract_features.py script, requiring only minimal changes to the workflow.

    • ONNX feature extraction: Use cn_clip/eval/extract_features_onnx.py
    • TensorRT feature extraction: Use cn_clip/eval/extract_features_tensorrt.py

    After extraction, the subsequent steps (KNN retrieval and Recall calculation) remain identical to the standard Pytorch workflow.

  7. Download the Zero-Shot Image Classification Dataset

    master

    The Chinese version of the ELEVATER Benchmark image classification benchmark is available for zero-shot classification with Chinese CLIP. It includes 20 datasets such as Caltech-101, CIFAR-10, CIFAR-100, and MNIST.

    Download the complete package (37GB) from Hugging Face: https://huggingface.co/datasets/OFA-Sys/chinese-clip-eval/resolve/main/ELEVATER_all.zip.

  8. Install the cn_clip package

    master

    You can install the latest stable release via pip, or install from the source code for development purposes.

    # to install the latest stable release
    pip install cn_clip
    
    # or install from source code
    cd Chinese-CLIP
    pip install -e .
  9. Convert PyTorch checkpoints to ONNX format

    master

    Use the cn_clip/deploy/pytorch_to_onnx.py script to convert Chinese-CLIP PyTorch checkpoints into ONNX format for deployment. The conversion produces both FP32 and FP16 versions for both text and vision models.

    Important: Some FP16 models generate an .extra_file. This file is required at runtime; the path to it is embedded within the .onnx file. To avoid runtime errors, use relative paths for the output directory during conversion.

    cd Chinese-CLIP/
    export CUDA_VISIBLE_DEVICES=0
    export PYTHONPATH=${PYTHONPATH}:`pwd`/cn_clip
    
    # Set your data path
    checkpoint_path=${DATAPATH}/pretrained_weights/clip_cn_vit-b-16.pt
    mkdir -p ${DATAPATH}/deploy/
    
    python cn_clip/deploy/pytorch_to_onnx.py \
           --model-arch ViT-B-16 \
           --pytorch-ckpt-path ${checkpoint_path} \
           --save-onnx-path ${DATAPATH}/deploy/vit-b-16 \
           --convert-text --convert-vision
  10. Organize Datasets for Zero-shot Evaluation

    master

    To use datasets with the project's code, they must follow a specific directory structure. After unzipping ELEVATER_all.zip and then unzipping the individual dataset files, each dataset directory (${dataset_name}) should look like this:

    • label_cn.txt: File containing Chinese labels (one per line). This is the primary file used in experiments.
    • label.txt: File containing English labels (one per line). Used for reference.
    • index.json: (Optional) Used only for ELEVATER benchmark submissions to specify test data order.
    • train/: Directory containing sub-directories for each category.
    • test/: Directory containing sub-directories for each category.

    Category Sub-directory Naming: Sub-directories must be named with IDs that correspond to the line index in the label files (0-indexed) and must be alphabetically ordered:

    • For $\le 10$ labels: Use IDs 0, 1, ..., 9.
    • For $> 10$ labels: Use 3-digit IDs with left-padding, e.g., 000, 001, ..., 099.
    ${dataset_name}
    ├── index.json  # Optional: for ELEVATER submission
    ├── label_cn.txt  # Chinese labels (used in experiments)
    ├── label.txt  # English labels (reference only)
    ├── test/
    │   ├── 000/
    │   ├── 001/
    │   └── 002/
    └── train/
        ├── 000/
        ├── 001/
        └── 002/
  11. Prepare environment for FlashAttention in Chinese-CLIP

    master

    To use FlashAttention acceleration in Chinese-CLIP, ensure your environment meets the following requirements:

    • GPU Architecture: Nvidia GPUs with Turing, Ampere, Ada, or Hopper architecture (e.g., H100, A100, RTX 3090, T4, RTX 2080).
    • CUDA: Version 11.4 or higher.
    • PyTorch: Version 1.12 or higher.
    • FlashAttention: Must be installed via pip.
    pip install flash-attn