Model Loaders API¶
This page documents the model loading components of the Segmentation Robustness Framework.
Model Loaders¶
segmentation_robustness_framework.loaders.models.universal_loader
¶
Classes¶
UniversalModelLoader()
¶
Universal model loader that handles different model types and wraps them with adapters.
Supported model types
- 'torchvision'
- 'smp'
- 'huggingface'
- 'custom'
Source code in segmentation_robustness_framework/loaders/models/universal_loader.py
Functions¶
load_model(model_type: str, model_config: dict[str, Any], weights_path: Optional[str] = None, weight_type: str = 'full', adapter_cls: Optional[type] = None) -> nn.Module
¶
Load model using appropriate loader and wrap with the correct adapter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_type
|
str
|
Model type identifier. Supported values:
- |
required |
model_config
|
dict[str, Any]
|
Configuration for model loading. |
required |
weights_path
|
Optional[str]
|
Path to weights file (optional). |
None
|
weight_type
|
str
|
Type of weights to load ('full' or 'encoder'). |
'full'
|
adapter_cls
|
Optional[type]
|
Adapter class to wrap the model. If provided, this adapter will be used instead of the default adapter for the model type. |
None
|
Returns:
| Type | Description |
|---|---|
Module
|
nn.Module: Loaded and adapted model. |
Source code in segmentation_robustness_framework/loaders/models/universal_loader.py
Functions¶
segmentation_robustness_framework.loaders.models.torchvision_loader
¶
Classes¶
TorchvisionModelLoader
¶
Bases: BaseModelLoader
Loader for torchvision segmentation models.
Supports loading models and weights, including encoder-only weights. Uses the 'weights' argument as recommended by torchvision >=0.13.
Supported model_config keys
name(str): Model name.num_classes(int): Number of classes (optional).weights(str | TorchvisionWeightsEnum): Torchvision weights enum, string, or None (optional).
Example
Functions¶
load_model(model_config: dict[str, Any]) -> nn.Module
¶
Load a torchvision segmentation model using the 'weights' argument.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_config
|
dict
|
|
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the model name is not supported. |
Returns:
| Type | Description |
|---|---|
Module
|
|
Source code in segmentation_robustness_framework/loaders/models/torchvision_loader.py
load_weights(model: nn.Module, weights_path: str | Path, weight_type: str = 'full') -> nn.Module
¶
Load weights into a torchvision model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Model instance. |
required |
weights_path
|
str | Path
|
Path to weights file. |
required |
weight_type
|
str
|
|
'full'
|
Supported weight_type values
'full': Load entire model weights.'encoder': Load encoder weights only.
Returns:
| Type | Description |
|---|---|
Module
|
|
Source code in segmentation_robustness_framework/loaders/models/torchvision_loader.py
segmentation_robustness_framework.loaders.models.smp_loader
¶
Classes¶
SMPModelLoader
¶
Bases: BaseModelLoader
Loader for segmentation_models_pytorch (SMP) models.
Supports loading models and weights, including encoder-only weights.
Supported model_config keys
architecture(str): Architecture of the model (default:'unet').encoder_name(str): Name of the encoder (default:'resnet34').encoder_weights(str): Weights of the encoder (default:'imagenet').classes(int): Number of classes (default:1).activation(str): Activation function (default:None).checkpoint(str | Path): Path to the checkpoint (default:None).
Example
Example
Example
Functions¶
load_model(model_config: dict[str, Any]) -> nn.Module
¶
Load an SMP model from config or checkpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_config
|
dict[str, Any]
|
|
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the checkpoint cannot be loaded. |
Returns:
| Type | Description |
|---|---|
Module
|
|
Source code in segmentation_robustness_framework/loaders/models/smp_loader.py
load_weights(model: nn.Module, weights_path: str, weight_type: str = 'full') -> nn.Module
¶
Load weights into SMP model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Model instance. |
required |
weights_path
|
str | Path
|
Path to weights file. |
required |
weight_type
|
str
|
|
'full'
|
Supported weight_type values
'full': Load entire model weights.'encoder': Load encoder weights only.
Returns:
| Type | Description |
|---|---|
Module
|
|
Source code in segmentation_robustness_framework/loaders/models/smp_loader.py
segmentation_robustness_framework.loaders.models.huggingface_loader
¶
Classes¶
HuggingFaceModelLoader
¶
Bases: BaseModelLoader
Loader for HuggingFace models.
Supported model_config keys
model_name(str): HuggingFace model id or path (required).num_labels(int): Number of output classes (optional).trust_remote_code(bool): Allow loading custom code from model repo (optional).task(str): "semantic_segmentation", "instance_segmentation", "panoptic_segmentation", "image_segmentation" (optional).return_processor(bool): Whether to return processor along with model (default: True).config_overrides(dict): Arbitrary config attributes to override (optional).processor_overrides(dict): Arbitrary processor attributes to override (optional).
Example
Example
# With config and processor overrides
loader = HuggingFaceModelLoader()
model_config = {
"model_name": "nvidia/segformer-b2-finetuned-ade-512-512",
"num_labels": 150,
"config_overrides": {"ignore_mismatched_sizes": True},
"processor_overrides": {"do_resize": False},
}
bundle = loader.load_model(model_config)
Example
Functions¶
load_model(model_config: dict[str, Any]) -> HFSegmentationBundle | nn.Module
¶
Load HuggingFace model and optionally its processor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_config
|
dict[str, Any]
|
|
required |
Returns:
| Type | Description |
|---|---|
HFSegmentationBundle | Module
|
|
Source code in segmentation_robustness_framework/loaders/models/huggingface_loader.py
load_weights(model: nn.Module, weights_path: str, weight_type: str = 'full') -> nn.Module
¶
Load weights into HuggingFace model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Model instance. |
required |
weights_path
|
str | Path
|
Path to weights file. |
required |
weight_type
|
str
|
'full' for entire model, 'encoder' for encoder only. |
'full'
|
Returns:
| Type | Description |
|---|---|
Module
|
|
Source code in segmentation_robustness_framework/loaders/models/huggingface_loader.py
segmentation_robustness_framework.loaders.models.custom_loader
¶
Classes¶
CustomModelLoader
¶
Bases: BaseModelLoader
Loader for custom user models.
Supported model_config keys
model_class(str | Callable[..., Any]): Model class or factory function (required).model_args(list[Any]): List of positional arguments for model initialization (optional).model_kwargs(dict[str, Any]): Dict of keyword arguments for model initialization (optional).
Example
Functions¶
load_model(model_config: dict[str, Any]) -> nn.Module
¶
Load custom model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_config
|
dict[str, Any]
|
|
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Returns:
| Type | Description |
|---|---|
Module
|
|
Source code in segmentation_robustness_framework/loaders/models/custom_loader.py
load_weights(model: nn.Module, weights_path: str, weight_type: str = 'full') -> nn.Module
¶
Load weights into custom model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Model instance. |
required |
weights_path
|
str | Path
|
Path to weights file. |
required |
weight_type
|
str
|
|
'full'
|
Supported weight_type values
'full': Load entire model weights.'encoder': Load encoder weights only.
Returns:
| Type | Description |
|---|---|
Module
|
|
Source code in segmentation_robustness_framework/loaders/models/custom_loader.py
Model Loading Overview¶
The framework provides specialized loaders for different model types, each designed to handle the specific requirements and output formats of different model architectures.
Universal Model Loader¶
The UniversalModelLoader is the main entry point for model loading. It automatically selects the appropriate specialized loader based on the model type.
from segmentation_robustness_framework.loaders import UniversalModelLoader
# Load a torchvision model
model = UniversalModelLoader().load_model(
model_type="torchvision",
model_config={"name": "deeplabv3_resnet50", "num_classes": 21}
)
# Load an SMP model
model = UniversalModelLoader().load_model(
model_type="smp",
model_config={"architecture": "unet", "encoder_name": "resnet34", "classes": 21}
)
# Load a HuggingFace model
model = UniversalModelLoader().load_model(
model_type="huggingface",
model_config={"model_name": "nvidia/segformer-b0-finetuned-ade-512-512"}
)
Supported Model Types¶
Torchvision Models¶
# Available models
torchvision_models = [
"deeplabv3_resnet50",
"deeplabv3_resnet101",
"deeplabv3_mobilenetv3_large",
"fcn_resnet50",
"fcn_resnet101",
"lraspp_mobilenet_v3_large"
]
# Example usage
model = UniversalModelLoader().load_model(
model_type="torchvision",
model_config={"name": "deeplabv3_resnet50", "num_classes": 21}
)
# With custom weights
model = UniversalModelLoader().load_model(
model_type="torchvision",
model_config={
"name": "deeplabv3_resnet50",
"num_classes": 21,
"weights": "COCO_WITH_VOC_LABELS_V1"
}
)
SMP Models¶
# Available architectures
smp_architectures = [
"unet", "unetplusplus", "manet", "linknet",
"fpn", "pspnet", "pan", "deeplabv3", "deeplabv3plus"
]
# Available encoders
smp_encoders = [
"resnet18", "resnet34", "resnet50", "resnet101", "resnet152",
"resnext50_32x4d", "resnext101_32x8d",
"timm-efficientnet-b0", "timm-efficientnet-b1", "timm-efficientnet-b2"
]
# Example usage
model = UniversalModelLoader().load_model(
model_type="smp",
model_config={
"architecture": "unet",
"encoder_name": "resnet34",
"encoder_weights": "imagenet",
"classes": 21
}
)
HuggingFace Models¶
# Example usage
model = UniversalModelLoader().load_model(
model_type="huggingface",
model_config={
"model_name": "nvidia/segformer-b0-finetuned-ade-512-512",
"trust_remote_code": True
}
)
# With additional configuration
model = UniversalModelLoader().load_model(
model_type="huggingface",
model_config={
"model_name": "nvidia/segformer-b0-finetuned-ade-512-512",
"num_labels": 150,
"config_overrides": {"ignore_mismatched_sizes": True},
"processor_overrides": {"do_resize": False}
}
)
Custom Models¶
For custom models, you can use the CustomModelLoader:
from segmentation_robustness_framework.loaders import CustomModelLoader
class MyCustomModel(nn.Module):
def __init__(self, num_classes=21):
super().__init__()
# Your model architecture here
pass
def forward(self, x):
# Your forward pass
return logits
# Load custom model
model = CustomModelLoader().load_model(
model_type="custom",
model_config={"model_class": MyCustomModel, "num_classes": 21}
)
Model Configuration¶
Each model type accepts different configuration parameters:
Torchvision Configuration¶
model:
type: torchvision
config:
name: deeplabv3_resnet50
num_classes: 21
weights: COCO_WITH_VOC_LABELS_V1 # Optional: specify weights
SMP Configuration¶
model:
type: smp
architecture: unet
encoder_name: resnet34
encoder_weights: imagenet
classes: 21
activation: None # Optional
HuggingFace Configuration¶
model:
type: huggingface
config:
model_name: nvidia/segformer-b0-finetuned-ade-512-512
trust_remote_code: true
num_labels: 150
Error Handling¶
The model loaders include comprehensive error handling: