Custom Models
This guide explains how to add a new model to DX-ModelZoo. All you need is a single YAML file and, optionally, custom preprocessing/postprocessing operations.
Before creating custom models, make sure you have:
- Installed DX-ModelZoo with development dependencies
- Basic understanding of YAML configuration
- Model file in ONNX format (or other supported formats)
- Familiarity with preprocessing/postprocessing concepts
Decision Flow
Creating a model involves the following 3 steps:
Step 1: Creating YAML File
Model YAML files are organized by domain, task, and model family:
Directory structure:
src/dx_modelzoo/models/
└── <domain>/ # e.g., cv, nlp, audio
└── <task>/ # e.g., image_classification, object_detection
└── <Family>/ # e.g., ResNet, EfficientNet
└── <ModelName>.yaml
Example:
src/dx_modelzoo/models/
└── cv/
└── image_classification/
└── MyModel/
└── MyModel_v1.yaml ← create here
Environment Variables in YAML
DX-ModelZoo supports environment variable substitution in YAML files (e.g. ${DATA_ROOT}, ${MODEL_ROOT}, ${MODEL_NAME}, ${DXMZ_MODEL_URL}). See YAML Configuration for the full list and syntax.
Minimal YAML Example
name: MyModel_v1
task: image_classification
inputs:
- name: input
shape: [1, 3, 224, 224]
dtype: float32
preprocessing:
- type: resize
size: [224, 224]
postprocessing:
- type: topk
k: [1, 5]
evaluator:
type: image_classification
dataset:
type: ILSVRC2012
eval_path: ${DATA_ROOT}/ILSVRC2012/val
artifacts:
path: ${MODEL_ROOT}/${MODEL_NAME}
profiles:
onnx:
target: onnx
runtime:
device: gpu
batch_size: 1
See YAML Configuration for the complete field reference, including multi-step preprocessing pipelines, NPU (q-lite/q-pro) profiles, and calibration settings.
When using built-in types for preprocessing, postprocessing, datasets, and evaluators, the model can be fully defined in YAML alone — no Python code required.
Step 2: Custom Operations
If the built-in types are insufficient, create a custom_ops.py file in the same directory as your model YAML:
src/dx_modelzoo/models/
└── cv/
└── image_classification/
└── MyModel/
├── MyModel_v1.yaml
└── custom_ops.py ← create here
Custom Preprocessing
import numpy as np
from dx_modelzoo.preprocessing import PREPROCESSING_REGISTRY
@PREPROCESSING_REGISTRY.register("my_letterbox")
class MyLetterbox:
"""Aspect-ratio-preserving resize with padding"""
def __init__(self, target_size: list[int], pad_value: int = 114):
self.target_size = tuple(target_size) # (H, W)
self.pad_value = pad_value
def __call__(self, img: np.ndarray) -> np.ndarray:
h, w = img.shape[:2]
th, tw = self.target_size
scale = min(tw / w, th / h)
new_w, new_h = int(w * scale), int(h * scale)
import cv2
resized = cv2.resize(img, (new_w, new_h))
canvas = np.full((th, tw, 3), self.pad_value, dtype=np.uint8)
top = (th - new_h) // 2
left = (tw - new_w) // 2
canvas[top:top + new_h, left:left + new_w] = resized
return canvas
Custom Postprocessing
from dx_modelzoo.postprocessing import POSTPROCESSING_REGISTRY
@POSTPROCESSING_REGISTRY.register("my_decode")
class MyDecode:
"""Custom decoding logic"""
def __init__(self, conf_threshold: float = 0.25):
self.conf_threshold = conf_threshold
def __call__(self, outputs: list[np.ndarray], **kwargs) -> dict:
# kwargs carries pipeline context (runtime_target, and origin_hw/input_hw
# for detection models) — always accept **kwargs
predictions = outputs[0]
mask = predictions[..., 4] > self.conf_threshold
return {"detections": predictions[mask]}
PostprocessingPipeline forwards context keyword arguments to every step.
A __call__(self, outputs) signature raises
TypeError: __call__() got an unexpected keyword argument 'runtime_target'.
For coordinate outputs, rescale with origin_hw / input_hw — see
Postprocessing API.
Using Custom Operations in YAML
preprocessing:
- type: my_letterbox # custom type
target_size: [640, 640]
pad_value: 114
- type: div
x: 255
- type: transpose
axis: [2, 0, 1]
- type: expanddim
axis: 0
postprocessing:
- type: my_decode # custom type
conf_threshold: 0.3
custom_ops.py placed in the same directory as the model YAML is automatically imported by ModelBuilder. No manual import is needed — just define your classes with @REGISTRY.register() and they become available in the YAML configuration.
Step 3: Verification
Run the evaluation to confirm the model works as expected:
# Run by model name
dxmz eval MyModel_v1 --profile onnx
# Expected output:
# Loading model: MyModel_v1
# Dataset: ILSVRC2012 (50000 samples)
# Evaluating... [============================] 100%
# Top-1 Accuracy: 76.13%
# Top-5 Accuracy: 92.86%
# FPS: 245.3
# Run with dataset path override
dxmz eval MyModel_v1 --profile onnx --data-root /path/to/datasets
# Run by YAML path
dxmz eval path/to/MyModel_v1.yaml --profile onnx
# Specify model file directly
dxmz eval MyModel_v1 --profile onnx --model-path /path/to/model.onnx
Complete Example
A full custom detection model configuration:
name: MyDet_s
task: object_detection
reference: https://github.com/my-org/mydet
description: >
Lightweight object detection model (COCO mAP 42.1)
inputs:
- name: images
shape: [1, 3, 640, 640]
dtype: float32
layout: NCHW
preprocessing:
- type: my_letterbox
target_size: [640, 640]
- type: convertcolor
form: BGR2RGB
- type: div
x: 255
- type: transpose
axis: [2, 0, 1]
- type: expanddim
axis: 0
postprocessing:
- type: my_decode
conf_threshold: 0.25
evaluator:
type: object_detection
dataset:
type: COCO
eval_path: ${DATA_ROOT}/COCO
artifacts:
path: ${MODEL_ROOT}/${MODEL_NAME}
calibration: &calibration
method: ema
num: 100
seed: 42
profiles:
onnx:
target: onnx
runtime:
device: gpu
q-lite:
target: dxnn
compile:
calibration: *calibration
runtime:
device: 0
async: true
q-pro:
target: dxnn
compile:
calibration:
<<: *calibration
num: 1024
use_q_pro: true
runtime:
device: 0
async: true
Model-Specific Evaluator Integration
For models that require custom decoding of model outputs (e.g., pose estimation, text detection), the recommended pattern is:
- Step 1. Define the decoder in
custom_ops.pywith@POSTPROCESSING_REGISTRY.register() - Step 2. Reference it in the YAML
postprocessingsection - Step 3. The evaluator receives the decoded output in
process_batch_result()
Example: Full Pipeline
@POSTPROCESSING_REGISTRY.register("db_text_decode")
class DBTextDecode:
"""Binarise DB probability map → list of polygon arrays."""
def __init__(self, db_thresh=0.3, db_box_thresh=0.5, **kwargs):
self.db_thresh = db_thresh
self.db_box_thresh = db_box_thresh
def __call__(self, outputs, **kwargs):
prob_map = outputs[0]
# ... decode logic ...
return polygons # List[np.ndarray [4,2]]
postprocessing:
- type: db_text_decode
db_thresh: 0.3
db_box_thresh: 0.5
evaluator:
type: text_detection
The evaluator then receives polygons directly and only computes IoU-based precision/recall metrics.
text_detection is not a built-in evaluatorThere is no registered text_detection evaluator (nor a TextDetectionEvaluator)
in v1.0.0. The example above assumes you register your own evaluator under
that key with @EVALUATOR_REGISTRY.register("text_detection"); otherwise the
build fails with an unknown-evaluator error. See
Evaluator API — Writing a Custom Evaluator.
Pipeline Evaluators (Multi-Model)
Some evaluators orchestrate multiple models (e.g., OCR = Detection + Recognition). In these cases:
- The evaluator manages session lifecycle and data flow
- Each model's decode logic still lives in its respective
custom_ops.py - The evaluator calls postprocessors explicitly via lazy-init imports
# Inside OCR Evaluator (simplified)
def process_batch_result(self, batch_data, output, metrics_state):
# Det model output → polygons (via custom_ops)
polygons = self._get_db_decoder()([output])
for poly in polygons:
crop = extract_crop(image, poly) # evaluator logic
rec_input = self._get_rec_preprocessor()(crop) # custom_ops
rec_output = self.rec_session.run(rec_input) # session
text = self._get_ctc_decoder()(rec_output) # custom_ops
# Compute Deteval metrics (evaluator logic)
...
Troubleshooting
| Item | Check |
|---|---|
Is the YAML file located under models/<domain>/<task>/<Family>/? | ✅ |
Does the name field match the filename? | ✅ |
Do the inputs shape/dtype match the model? | ✅ |
Are custom ops registered with @REGISTRY.register()? | ✅ |
Is custom_ops.py in the same directory as the YAML? | ✅ |
Are custom postprocessors receiving **kwargs? | ✅ |
Are the required runtimes defined in profiles? | ✅ |
Does dxmz eval run successfully? | ✅ |