MedSigLIP

repository·main·Indexed 43 days ago

https://github.com/google-health/medsiglip

A medical-specialized vision-language model based on SigLIP designed to map medical images and text into a shared embedding space. It features a 400M parameter vision encoder and a 400M parameter text encoder, supporting 448x448 image resolution. MedSigLIP is used for data-efficient classification, zero-shot classification, and semantic image retrieval. The documentation provides workflows for local execution via Hugging Face, deployment on Vertex AI Model Garden, and fine-tuning for contrastive image-text learning or multi-label image classification.

Tokens
8K
Snippets
25
Records
32
Agent score
55%

What's inside MedSigLIP

  1. Overview of MedSigLIP

    main

    MedSigLIP is a variant of SigLIP (Sigmoid Loss for Language Image Pre-training) specifically trained to encode medical images and text into a shared embedding space. It is designed for medical image interpretation tasks that do not require text generation.

    Key Capabilities:

    • Use Cases: Data-efficient classification, zero-shot classification, and semantic image retrieval.
    • Model Architecture: Contains a 400M parameter vision encoder and a 400M parameter text encoder.
    • Input Specifications: Supports 448x448 image resolution and up to 64 text tokens.

    Note: If your application requires text generation, use MedGemma instead.

  2. Overview of the MedSigLIP Serving Framework

    main

    The MedSigLIP serving framework is a Python library designed to simplify the creation of custom prediction containers for Vertex AI. It provides a structured way to build HTTP servers that comply with Vertex AI custom container requirements.

    Developers should use this framework to implement model-specific HTTP servers by wrapping custom data handling and orchestration logic within the provided framework structures.

  3. Train a data-efficient classifier using embeddings

    main
    Use the train_data_efficient_classifier.ipynb notebook to train a custom classifier. This method leverages pre-generated MedSigLIP image embeddings, allowing for effective training with reduced data and compute requirements.
    train_data_efficient_classifier.ipynb
  4. Download MedSigLIP pre-processor configuration files

    main

    The pre-processor configuration files required for MedSigLIP can be downloaded from the official Hugging Face repository. These files are necessary for correctly preparing input data for the model.

    Download them from: https://huggingface.co/google/siglip-base-patch16-224/tree/main

    https://huggingface.co/google/siglip-base-patch16-224/tree/main
  5. Get started with MedSigLIP

    main

    To begin using MedSigLIP, you can follow these paths depending on your deployment preference:

    1. Developer Documentation: Access the full range of next steps and the model card via the official developer portal.
    2. Hugging Face / Model Garden: Access the model weights directly on Hugging Face or via Google Cloud's Model Garden.
    3. Local/Notebook Exploration: Use the provided notebooks in this repository to learn how to use the model with Hugging Face and Vertex AI.
    4. Vertex AI Deployment: Use the implementation found in python/serving to build a container for deployment to Vertex AI.
  6. Compare Online vs Batch predictions in MedSigLIP

    main

    MedSigLIP supports two primary prediction methods in Vertex AI:

    • Online predictions: Synchronous requests made to a deployed Vertex AI Endpoint. These are served with low latency and are ideal for production environments where immediate responses are required. Costs are based on the active time of the virtual machine hosting the endpoint.
    • Batch predictions: Asynchronous requests run on a set of inputs (images or text) specified in a single job. These are made directly to a model in the Vertex AI Model Registry without requiring a deployed endpoint. They are ideal for generating embeddings for large datasets (e.g., for training) where low latency is not a priority. Costs are based on the time the virtual machine spends running the specific prediction job.
  7. Resize images for MedSigLIP evaluation reproduction

    main

    While the transformers image processor handles resizing automatically using PIL.Image.resize, you can use tf.image.resize to exactly match the resizing implementation used in MedSigLIP evaluations (based on the Big Vision library).

    Use tf.image.resize with method='bilinear' and antialias=False to target the INPUT_DIMENSION (e.g., [448, 448]).

    from tensorflow.image import resize as tf_resize
    import numpy as np
    from PIL import Image
    
    INPUT_DIMENSION = [448, 448]
    
    def resize(image):
        return Image.fromarray(
            tf_resize(
                images=image, size=INPUT_DIMENSION, method='bilinear', antialias=False
            ).numpy().astype(np.uint8)
        )
    
    imgs = [resize(img) for img in imgs]
  8. Run batch predictions with MedSigLIP

    main

    Batch predictions are performed by uploading the model to the Vertex AI Model Registry and then submitting a batch job.

    1. Upload Model: Use aiplatform.Model.upload() with the MedSigLIP serving container image and appropriate environment variables (MODEL_INPUT_WIDTH, MODEL_INPUT_HEIGHT, etc.).
    2. Prepare Input: Create a JSON Lines (.jsonl) file where each line is a prediction instance (e.g., {"image": {"gcs_uri": "..."}} or {"text": "..."}).
    3. Upload Input to GCS: Upload the .jsonl file to a Cloud Storage bucket.
    4. Submit Job: Call model.batch_predict() specifying the gcs_source (the .jsonl file) and gcs_destination_prefix (where results will be stored).
    # Example: Batch prediction for images from GCS
    # batch_predict_instances is a list of dicts like {"image": {"gcs_uri": uri}}
    
    # 1. Write to JSONL
    with open("input.jsonl", "w") as f:
        for line in batch_predict_instances:
            f.write(json.dumps(line) + "\n")
    
    # 2. Upload to GCS
    ! gcloud storage cp input.jsonl gs://your-bucket/input/input.jsonl
    
    # 3. Run Job
    job = models["model"].batch_predict(
        job_display_name="my-batch-job",
        gcs_source="gs://your-bucket/input/input.jsonl",
        gcs_destination_prefix="gs://your-bucket/output",
        machine_type="n1-standard-8",
        accelerator_type="NVIDIA_TESLA_T4",
        accelerator_count=1,
        service_account=SERVICE_ACCOUNT,
    )
    job.wait()