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:
| File | Purpose |
|---|---|
config.yaml | Python version, CPU or GPU, and other build settings |
mdai_deploy.py | An MDAIModel class that loads the model and returns predictions |
requirements.txt | Python packages to install |
model/
├── .mdai/
│ ├── config.yaml
│ ├── mdai_deploy.py
│ ├── requirements.txt
│ └── helpers.py # optional helper modules
└── model_file.pthThe 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| Key | Required | Values |
|---|---|---|
device_type | ✓ | cpu or gpu |
base_image | Python 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_version | For gpu: 10.0, 10.1, 11.0 (default), 11.3, 11.8, 12.1, 12.2, 12.3 or 12.4 | |
batch_size | How many inputs the model receives at once. Fixes the batch size in the runtime config. | |
env | Environment 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 outputsConvert 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 Typeset toDICOM, each file is a DICOM file. Read it withpydicom.dcmread(BytesIO(file["content"])). - With
Thumbnail, or for PNG and JPEG images in cloud storage datasets, each file is a PNG or JPEG, anddicom_tagsholds its DICOM tags, including the UIDs to return. - With
Input Data Sourceset toDisk,contentisNone; read the file fromcontent_pathinstead. Use it for large inputs. - A multi-frame DICOM is sent once, as a single file. Return a 0-based
frame_numberwith 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:
| Key | Type | Description |
|---|---|---|
type | str | ANNOTATION, IMAGE, DICOM or NONE. Required. |
study_uid | str | Required. |
series_uid | str | Required for series- and image-level outputs. |
instance_uid | str | Required for image-level outputs. |
class_index | int | The class, as mapped to a label on the model card. Required except for NONE. |
data | dict | The shape, for local labels. See Annotation data. |
probability | float or list | The probability of class_index, or every class's probability: [{"class_index": 0, "probability": 0.1}, ...] |
note | str | Text shown with the output and in the Notes panel. |
explanations | list | Extra results to display, such as Grad-CAM heatmaps. See the X-ray classification example. |
frame_number | int | 0-based frame, for multi-frame inputs. |
video_frame_number | int | 0-based frame, for image-level outputs on videos. |
images | list | For IMAGE and DICOM outputs. See Image outputs. |
image_output_tags | dict | For 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:
| Mode | data |
|---|---|
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, inclusiveReturn 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",
},
}
)
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.2You 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.whlMD.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