MD.ai

Model Interface

The files that connect your model to MD.ai, and the input and output formats

To run on MD.ai, your model needs three files in a .mdai folder next to your weights:

FilePurpose
config.yamlPython version, CPU or GPU, and other build settings
mdai_deploy.pyAn MDAIModel class that loads the model and returns predictions
requirements.txtPython packages to install
model/
├── .mdai/
│   ├── config.yaml
│   ├── mdai_deploy.py
│   ├── requirements.txt
│   └── helpers.py        # optional helper modules
└── model_file.pth

The model folder and the .mdai folder are both on the Python path, so mdai_deploy.py can import modules from either. Import modules in other subfolders as packages, for example from utils.preprocess import resize.

To get started, download the skeleton code and fill it in. The .mdai folder is hidden on most systems, so turn on hidden files to see it. For complete working models, see the model-deploy examples.

Once the files are ready, deploy the model.

config.yaml

base_image: py313
device_type: gpu
cuda_version: 12.1
KeyRequiredValues
device_type✓cpu or gpu
base_imagePython version: py39, py310, py311, py312, py313 or py314 (default). Use an older version if a package doesn't support the newest Python yet; for example, TensorFlow needs py313 or earlier. py37 and py38 are no longer supported. Advanced builds can use custom, with your own .mdai/Dockerfile, or nvidia for NVIDIA Clara (with clara_version: 4.1.0).
cuda_versionFor gpu: 10.0, 10.1, 11.0 (default), 11.3, 11.8, 12.1, 12.2, 12.3 or 12.4
batch_sizeHow many inputs the model receives at once. Fixes the batch size in the runtime config.
envEnvironment variables to set in the container, as a map

The model is built on Google Cloud's Deep Learning container images, with a conda environment for your Python version.

mdai_deploy.py

Define a class named MDAIModel with two methods:

  • __init__(self): load the model, once, when the container starts.
  • predict(self, data): run the model on a batch of inputs and return a list of outputs.
import os
from io import BytesIO

import pydicom


class MDAIModel:
    def __init__(self):
        root = os.path.dirname(os.path.dirname(__file__))  # the `model` folder
        self.model = load_model(os.path.join(root, "model_file.pth"))  # your loading code

    def predict(self, data):
        outputs = []

        for file in data["files"]:
            if file["content_type"] != "application/dicom":
                continue

            ds = pydicom.dcmread(BytesIO(file["content"]))
            image = ds.pixel_array

            class_index, probability = self.model.classify(image)  # your inference code

            outputs.append(
                {
                    "type": "ANNOTATION",
                    "study_uid": str(ds.StudyInstanceUID),
                    "series_uid": str(ds.SeriesInstanceUID),
                    "instance_uid": str(ds.SOPInstanceUID),
                    "class_index": int(class_index),
                    "probability": float(probability),
                }
            )

        return outputs

Convert values to plain Python types (int, float, str, list) as shown: NumPy types fail validation.

Input

predict receives data, a dictionary:

{
    "files": [
        {
            "content": bytes,         # the file; None when the input data source is Disk
            "content_path": str,      # path to the file, when the input data source is Disk
            "content_type": str,      # "application/dicom", "image/png" or "image/jpeg"
            "dicom_tags": dict,       # for PNG/JPEG inputs: the DICOM tags of the image
        },
        # ...
    ],
    "annotations": [                  # existing annotations of the model's labels
        {
            "id": str,
            "label_id": str,
            "study_uid": str,
            "series_uid": str,
            "instance_uid": str,
            "frame_number": int,
            "data": dict,
            "note": str,
            "parent_id": str,
        },
        # ...
    ],
    "label_classes": [                # the model's label classes
        {
            "class_index": int,
            "label": {
                "id": str,
                "name": str,
                "short_name": str,
                "description": str,
                "type": str,          # "GLOBAL" or "LOCAL"
                "scope": str,         # "STUDY", "SERIES" or "INSTANCE"
                "annotation_mode": str,
                "parent_id": str,
            },
        },
        # ...
    ],
    "args": {"key": "value"},         # model args, as set for this run
    "input_data_source": str,         # "MEMORY" or "DISK"
}

files depends on the model's scope: one image for Image, every image in the series for Series, every image in the exam for Exam.

  • With Input File Type set to DICOM, each file is a DICOM file. Read it with pydicom.dcmread(BytesIO(file["content"])).
  • With Thumbnail, or for PNG and JPEG images in cloud storage datasets, each file is a PNG or JPEG, and dicom_tags holds its DICOM tags, including the UIDs to return.
  • With Input Data Source set to Disk, content is None; read the file from content_path instead. Use it for large inputs.
  • A multi-frame DICOM is sent once, as a single file. Return a 0-based frame_number with each output to place it on the right frame.

Batching. To process several inputs at once, define predict_batch(self, data). It receives files as a list of lists, one list of files per input, up to the Batch Size. If you define only predict, it's called once per input, with a flat files list.

annotations contains existing annotations of the model's labels on the input, for models that refine or use human annotations. It's empty if Input Annotations is turned off for the version.

args holds the model args, with the values chosen for the run.

Images uploaded as JPEG or PNG

Images uploaded to MD.ai are converted to DICOM. See Working with DICOM converted from JPEG/PNG if your model expects the original images.

Output

predict returns a list of outputs. Each output is a dictionary:

KeyTypeDescription
typestrANNOTATION, IMAGE, DICOM or NONE. Required.
study_uidstrRequired.
series_uidstrRequired for series- and image-level outputs.
instance_uidstrRequired for image-level outputs.
class_indexintThe class, as mapped to a label on the model card. Required except for NONE.
datadictThe shape, for local labels. See Annotation data.
probabilityfloat or listThe probability of class_index, or every class's probability: [{"class_index": 0, "probability": 0.1}, ...]
notestrText shown with the output and in the Notes panel.
explanationslistExtra results to display, such as Grad-CAM heatmaps. See the X-ray classification example.
frame_numberint0-based frame, for multi-frame inputs.
video_frame_numberint0-based frame, for image-level outputs on videos.
imageslistFor IMAGE and DICOM outputs. See Image outputs.
image_output_tagsdictFor IMAGE outputs. See Image outputs.

Outputs with any other key are rejected. Use NONE to report that the model ran on an input but found nothing.

The UIDs identify the input the output belongs to, at the level of the label's scope: return study_uid for an exam-level label, study_uid and series_uid for a series-level label, and all three for image-level and local labels.

Annotation data

For local labels, data must match the label's annotation mode:

Modedata
Bounding Box{"x": int, "y": int, "width": int, "height": int}, where x, y is the top-left corner
Freeform, Polygon, Line{"vertices": [[x, y], [x, y], ...]}
Location{"x": int, "y": int}
Ellipse{"cx": float, "cy": float, "rx": float, "ry": float, "rotation": float}: center, radii, and rotation in degrees
Mask{"mask": [[0, 1, ...], ...]}: a 2D list the size of the image. Convert NumPy arrays with .tolist().

For example, returning mask data for a freeform label won't work. To turn a mask into an outline, use a contour function such as skimage.measure.find_contours.

Global labels don't need data, except to limit a series-level label on a video to some frames:

"data": {"start_frame_number": 0, "end_frame_number": 100}  # 0-based, inclusive

Return both keys, or neither to cover the whole video.

Image outputs

Models can return new images, such as generated or processed images, that users open in the viewer with Open Image in viewer. They can also be exported to a new dataset.

For PNG or JPEG images, use type: "IMAGE" and return the encoded images in images. Several images form a series, in list order:

from io import BytesIO
from PIL import Image

images = []
for array in generated_arrays:
    buffer = BytesIO()
    Image.fromarray(array).save(buffer, format="PNG")
    images.append(buffer.getvalue())

outputs.append(
    {
        "type": "IMAGE",
        "study_uid": str(ds.StudyInstanceUID),
        "series_uid": str(ds.SeriesInstanceUID),
        "instance_uid": str(ds.SOPInstanceUID),
        "class_index": 0,
        "note": "Generated image series",
        "images": images,
        # Optional: DICOM tags to use when the images are exported to a dataset
        "image_output_tags": {
            "PatientID": "anon-001",
            "StudyInstanceUID": "1.2.826.0.1.3680043.8.498.1",
            "SeriesInstanceUID": "1.2.826.0.1.3680043.8.498.2",
        },
    }
)
Opening an image output An image series output

For DICOM images, use type: "DICOM" and return the encoded DICOM files:

buffer = BytesIO()
generated_dataset.save_as(buffer)  # a pydicom Dataset

outputs.append(
    {
        "type": "DICOM",
        "study_uid": str(ds.StudyInstanceUID),
        "series_uid": str(ds.SeriesInstanceUID),
        "instance_uid": str(ds.SOPInstanceUID),
        "class_index": 0,
        "images": [buffer.getvalue()],
    }
)

The UIDs in the output are those of the input image, not of the generated images.

requirements.txt

List the Python packages your code imports, with pinned versions:

numpy==1.26.4
opencv-python-headless==4.9.0.80
pydicom==2.4.4
torch==2.2.2

You can also install from Git, from a find-links URL, or from wheel files placed in .mdai:

git+https://github.com/facebookresearch/detectron2.git

-f https://dl.fbaipublicfiles.com/detectron2/wheels/cu101/torch1.6/index.html
detectron2

./custom_wheel-0.1.0-py3-none-any.whl

MD.ai first installs the packages its model server needs, then yours, so your pinned versions take precedence. The model server is tested with these ranges, so stay within them where you can:

fastapi>=0.115,<1
uvicorn>=0.30,<1
msgpack>=1.1,<2
numpy>=1.24,<3
pydicom>=2.4,<4
pylibjpeg>=1.4,<3
pylibjpeg-libjpeg>=1.3,<3
pylibjpeg-openjpeg>=1.3,<3
pylibjpeg-rle>=1.3,<3
protobuf>=3.20,<8

On this page