跳转到主要内容
SDK Version: 2.5.0

Registry Pattern

The DX-ModelZoo uses the Registry pattern to manage all extensible components. The type field in YAML maps to classes registered in a Registry, enabling object creation from strings alone.

Registry Class​

Registry is a general-purpose class defined in src/dx_modelzoo/common/registry.py:

class Registry:
"""General-purpose registry managing name-to-class mappings"""

def __init__(self, name: str) -> None:
self.name = name
self._registry: dict[str, type] = {}

def register(self, name_or_cls: Union[str, type, None] = None):
"""Register a class via decorator.

Can be used as:
@REGISTRY.register("name") — explicit name
@REGISTRY.register — auto-derive from class name
"""
if name_or_cls is None or isinstance(name_or_cls, str):
explicit_name = name_or_cls
def decorator(cls):
key = explicit_name or _derive_name(cls)
self._registry[key] = cls
return cls
return decorator
else:
cls = name_or_cls
key = _derive_name(cls)
self._registry[key] = cls
return cls

def get(self, name: str) -> type:
"""Look up a class by name"""
if name not in self._registry:
raise KeyError(f"{self.name}: '{name}' not found")
return self._registry[name]

def list(self) -> list[str]:
"""Return all registered names"""
return list(self._registry.keys())

def __contains__(self, name: str) -> bool:
return name in self._registry

def __len__(self) -> int:
return len(self._registry)

Core Registries​

DX-ModelZoo defines four core registries:

RegistryLocationPurpose
PREPROCESSING_REGISTRYpreprocessing/__init__.pyPreprocessing operations
POSTPROCESSING_REGISTRYpostprocessing/__init__.pyPostprocessing operations
DATASET_REGISTRYdataset/__init__.pyDatasets
EVALUATOR_REGISTRYevaluator/__init__.pyEvaluators

Registration​

Registering a custom type follows a two-step pattern:

Decorator Pattern (Standard)​

from dx_modelzoo.preprocessing import PREPROCESSING_REGISTRY

@PREPROCESSING_REGISTRY.register("my_op")
class MyOp:
def __init__(self, param1: int = 10):
self.param1 = param1

def __call__(self, data):
# Processing logic
return data

Usage in YAML​

preprocessing:
- type: my_op # Looks up MyOp class from the Registry
param1: 20 # Instantiated as MyOp(param1=20)

Build Process​

When ModelBuilder parses YAML, it looks up classes through the Registry and creates instances:

Pipeline Build Process​

# Simplified internal logic of ModelBuilder.build_preprocessing()
def build_preprocessing(self, profile_name, ...):
steps = []
for step_config in self.config["preprocessing"]:
type_name = step_config["type"]
params = {k: v for k, v in step_config.items() if k != "type"}

# Look up class from Registry and instantiate with parameters
cls = PREPROCESSING_REGISTRY.get(type_name)
steps.append(cls(**params))

return PreprocessingPipeline(steps, npu_mode=is_npu)

Registered Types​

The following tables list all built-in registered types:

PREPROCESSING_REGISTRY​

NameClassParameters
resizeResizesize, mode, interpolation
centercropCenterCropheight, width
convertcolorConvertColorform
divDivx
normalizeNormalizemean, std
transposeTransposeaxis
expanddimExpandDimaxis
bgr_to_y_channelBgrToYChannel—
bgr_to_y_channel_uint8BgrToYChannelUint8—
mulMulx
addAddx
subtractSubtractx
totensorToTensor—

POSTPROCESSING_REGISTRY​

NameClassPurpose
identityIdentityNo postprocessing (passthrough)
topkTopKTop-k classes for classification
nmsNMSNon-maximum suppression (detection)
segmentation_argmaxSegmentationArgmaxSegmentation argmax

DATASET_REGISTRY​

NameTask
ILSVRC2012Classification
COCODetection / Instance Segmentation
PascalVOC2007Detection
PascalVOC2012Segmentation
CityscapesSegmentation
WiderFaceFace Detection
COCOPosePose Estimation
COCOPoseTopDownPose Estimation (Top-Down)
COCOPersonSegPerson Segmentation
NYUDepthv2Depth Estimation
LFWFace Recognition
BSD68 / BSD100 / CBSD68Super Resolution / Denoising
LOLLow-light Enhancement
ADE20KSegmentation
DOTAv1Oriented Object Detection
OxfordIIITPetSegmentation
Market1501Person Re-ID
PETAPedestrian Attribute
HandKeypointsHand Landmark
HandKeypointsDetectionHand Detection
Listing Registered Types
from dx_modelzoo.preprocessing import PREPROCESSING_REGISTRY
print(PREPROCESSING_REGISTRY.list())
# ['resize', 'centercrop', 'convertcolor', 'div', 'normalize', ...]

Adding Custom Types​

The same decorator pattern shown in Registration applies to any registry (PREPROCESSING_REGISTRY, POSTPROCESSING_REGISTRY, DATASET_REGISTRY, EVALUATOR_REGISTRY). For more details, see the Custom Model Guide and Custom Dataset Guide.

Auto-Import via custom_ops.py​

Model-specific postprocessing types don't need to be in the core postprocessing/ package. Instead, they can be defined in a custom_ops.py file within the model's directory.

How It Works​

Key Details​

  • Location: custom_ops.py must be in the same directory as the model YAML
  • Import timing: Imported during ModelBuilder.__init__(), before YAML validation
  • Module naming: Uses SHA1 hash of the file path to avoid module name collisions
  • Idempotent: If the same file is already loaded, the import is skipped
# ModelBuilder._import_custom_ops() (simplified)
def _import_custom_ops(self) -> None:
custom_ops_path = self.model_dir / "custom_ops.py"
if custom_ops_path.exists():
module_key = hashlib.sha1(str(custom_ops_path.resolve()).encode()).hexdigest()[:12]
module_name = f"custom_ops_{self.model_dir.name}_{module_key}"
spec = importlib.util.spec_from_file_location(module_name, custom_ops_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)