Pipeline API¶
This page documents the pipeline components of the Segmentation Robustness Framework.
segmentation_robustness_framework.pipeline.core
¶
Classes¶
SegmentationRobustnessPipeline(model: SegmentationModelProtocol, dataset: torch.utils.data.Dataset, attacks: list, metrics: list[Callable], batch_size: int = 8, device: str = 'cpu', output_dir: Optional[str] = None, auto_resize_masks: bool = True, metric_names: Optional[list[str]] = None, output_formats: list[str] = ['json', 'csv'], metric_precision: int = 4, num_workers: int = 0, pin_memory: bool = False, persistent_workers: bool = False)
¶
Pipeline for evaluating segmentation models under adversarial attacks.
This pipeline evaluates a segmentation model on clean and adversarial images, computes metrics, and provides hooks for saving results.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
SegmentationModelProtocol
|
Adapter-wrapped segmentation model. |
dataset |
Dataset
|
Dataset for evaluation. |
attacks |
list
|
List of attack instances (must implement call(images, targets)). |
metrics |
list[Callable]
|
List of metric functions/classes (accepting (targets, preds)). |
batch_size |
int
|
Batch size for evaluation. |
device |
str
|
Device to use for computation. |
output_dir |
str
|
Directory to save results. |
auto_resize_masks |
bool
|
Whether to automatically resize masks to model output size. |
Initialize the segmentation robustness pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
SegmentationModelProtocol
|
Segmentation model (adapter-wrapped). |
required |
dataset
|
Dataset
|
Dataset object. |
required |
attacks
|
list
|
List of attack instances. |
required |
metrics
|
list[Callable]
|
List of metric functions or classes. |
required |
batch_size
|
int
|
Batch size for evaluation. |
8
|
device
|
str
|
Device to use. |
'cpu'
|
output_dir
|
str
|
Directory to save results. |
None
|
auto_resize_masks
|
bool
|
Whether to automatically resize masks to model output size. |
True
|
metric_names
|
list[str]
|
Custom names for metrics. If None, auto-generate. |
None
|
output_formats
|
list[str]
|
List of output formats to save. Options: ["json", "csv"]. Defaults to ["json", "csv"] (save both). |
['json', 'csv']
|
metric_precision
|
int
|
Number of decimal places for metric values. Defaults to 4. |
4
|
num_workers
|
int
|
Number of workers for DataLoader. Defaults to 0 to prevent hanging. |
0
|
pin_memory
|
bool
|
Whether to pin memory in DataLoader. Defaults to False. |
False
|
persistent_workers
|
bool
|
Whether to use persistent workers. Defaults to False. |
False
|
Source code in segmentation_robustness_framework/pipeline/core.py
Functions¶
run(save: bool = False, show: bool = False) -> dict[str, Any]
¶
Run the evaluation pipeline: clean and adversarial evaluation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save
|
bool
|
Whether to save results (images, metrics, etc.). |
False
|
show
|
bool
|
Whether to show visualizations. |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Dictionary containing all evaluation results. |
Source code in segmentation_robustness_framework/pipeline/core.py
get_summary() -> dict[str, Any]
¶
Get a summary of the evaluation results.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Summary containing key statistics and comparisons. |
Source code in segmentation_robustness_framework/pipeline/core.py
print_summary() -> None
¶
Print a formatted summary of the evaluation results.
Source code in segmentation_robustness_framework/pipeline/core.py
get_run_info() -> dict[str, Any]
¶
Get information about the current run.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Dictionary containing run information. |
Source code in segmentation_robustness_framework/pipeline/core.py
evaluate_clean(loader: DataLoader) -> list[dict[str, Any]]
¶
Evaluate model on clean images.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loader
|
DataLoader
|
DataLoader for the dataset. |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
list[dict[str, Any]]: List of metric results for each batch. |
Source code in segmentation_robustness_framework/pipeline/core.py
evaluate_attack(loader: DataLoader, attack: Callable) -> list[dict[str, Any]]
¶
Evaluate model on adversarial images for a given attack.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loader
|
DataLoader
|
DataLoader for the dataset. |
required |
attack
|
Callable
|
Attack instance. |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
list[dict[str, Any]]: List of metric results for each batch. |
Source code in segmentation_robustness_framework/pipeline/core.py
compute_metrics(targets: torch.Tensor | np.ndarray, preds: torch.Tensor | np.ndarray) -> dict[str, Any]
¶
Compute all metrics for a batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
targets
|
Tensor | ndarray
|
Ground truth labels. |
required |
preds
|
Tensor | ndarray
|
Predicted labels. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Dictionary of metric results. |
Source code in segmentation_robustness_framework/pipeline/core.py
save_results(metrics: list[dict[str, Any]], name: str) -> None
¶
Save detailed batch metrics to disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metrics
|
list[dict[str, Any]]
|
List of metric results for each batch. |
required |
name
|
str
|
Name for the result set (e.g., 'clean', 'attack_FGSM'). |
required |
Source code in segmentation_robustness_framework/pipeline/core.py
Functions¶
Modules¶
segmentation_robustness_framework.pipeline.config
¶
Classes¶
PipelineConfig(config: dict[str, Any])
¶
Configuration parser and pipeline factory for segmentation robustness evaluation.
This class loads configuration from YAML/JSON files and creates ready-to-run segmentation robustness pipelines.
Configuration File Structure:
# Model configuration
model:
type: "torchvision" # torchvision, smp, huggingface, custom
config:
name: "deeplabv3_resnet50"
num_classes: 21
weights_path: null # optional
weight_type: "full" # full or encoder
adapter: null # optional custom adapter class
# Dataset configuration
dataset:
name: "ade20k"
root: null # will use cache directory
split: "val"
image_shape: [256, 256]
download: true
# Attack configurations
attacks:
- name: "fgsm"
eps: 0.02
- name: "pgd"
eps: 0.02
alpha: 0.01
iters: 10
targeted: false
# Pipeline configuration
pipeline:
batch_size: 8
device: "cuda"
output_dir: "./runs"
auto_resize_masks: true
output_formats: ["json", "csv"]
# Metrics configuration
metrics:
ignore_index: 255
selected_metrics:
- "mean_iou"
- "pixel_accuracy"
- {"name": "dice_score", "average": "micro"}
- "name_of_custom_metric"
Usage Examples:
# From YAML file
config = PipelineConfig.from_yaml("config.yaml")
pipeline = config.create_pipeline()
results = pipeline.run(save=True)
# From dictionary
config_dict = {
"model": {
"type": "torchvision",
"config": {"name": "deeplabv3_resnet50", "num_classes": 21}
},
"dataset": {
"name": "voc",
"root": "./data/VOCdevkit/VOC2012",
"split": "val",
"image_shape": [256, 256],
"download": false
},
"attacks": [{"name": "fgsm", "eps": 0.02}],
"pipeline": {"batch_size": 4, "device": "cuda", "auto_resize_masks": true}
}
config = PipelineConfig.from_dict(config_dict)
pipeline = config.create_pipeline()
results = pipeline.run()
Initialize configuration parser.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
dict[str, Any]
|
Configuration dictionary. |
required |
Source code in segmentation_robustness_framework/pipeline/config.py
Functions¶
from_yaml(config_path: Union[str, Path]) -> PipelineConfig
classmethod
¶
Create configuration from YAML file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_path
|
str | Path
|
Path to YAML configuration file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
PipelineConfig |
PipelineConfig
|
Configuration instance. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If config file doesn't exist. |
YAMLError
|
If YAML is malformed. |
Source code in segmentation_robustness_framework/pipeline/config.py
from_json(config_path: Union[str, Path]) -> PipelineConfig
classmethod
¶
Create configuration from JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_path
|
str | Path
|
Path to JSON configuration file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
PipelineConfig |
PipelineConfig
|
Configuration instance. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If config file doesn't exist. |
JSONDecodeError
|
If JSON is malformed. |
Source code in segmentation_robustness_framework/pipeline/config.py
from_dict(config: dict[str, Any]) -> PipelineConfig
classmethod
¶
Create configuration from dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
dict[str, Any]
|
Configuration dictionary. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
PipelineConfig |
PipelineConfig
|
Configuration instance. |
Source code in segmentation_robustness_framework/pipeline/config.py
create_pipeline() -> SegmentationRobustnessPipeline
¶
Create and configure a segmentation robustness pipeline.
Returns:
| Name | Type | Description |
|---|---|---|
SegmentationRobustnessPipeline |
SegmentationRobustnessPipeline
|
Configured pipeline ready to run. |
Source code in segmentation_robustness_framework/pipeline/config.py
run_pipeline(save: bool = True, show: bool = False) -> dict[str, Any]
¶
Create and run the pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save
|
bool
|
Whether to save results. Defaults to True. |
True
|
show
|
bool
|
Whether to show visualizations. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Pipeline results. |
Source code in segmentation_robustness_framework/pipeline/config.py
get_config_summary() -> dict[str, Any]
¶
Get a summary of the configuration.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Configuration summary. |
Source code in segmentation_robustness_framework/pipeline/config.py
Functions¶
Pipeline Configuration¶
The pipeline configuration system allows you to define complete experiments using YAML configuration files.
Configuration Structure¶
pipeline:
device: cuda
batch_size: 4
output_dir: results
auto_resize_masks: true
output_formats: ["json"]
model:
type: torchvision
config:
name: deeplabv3_resnet50
num_classes: 21
dataset:
name: voc
split: val
root: ./data
image_shape: [512, 512]
download: true
attacks:
- name: fgsm
eps: 0.02
- name: pgd
eps: 0.02
alpha: 0.02
iters: 10
targeted: false
metrics:
ignore_index: 255
selected_metrics:
- mean_iou
- pixel_accuracy
- precision
- recall
Pipeline Execution¶
The pipeline orchestrates the entire evaluation process:
- Model Loading: Loads the specified model with appropriate adapter
- Dataset Loading: Loads and preprocesses the dataset
- Attack Generation: Creates adversarial examples using specified attacks
- Evaluation: Runs both clean and adversarial evaluation
- Reporting: Generates comprehensive results and visualizations
Results Structure¶
The pipeline returns a dictionary with the following structure: