pathforge.inference¶
Inference helpers for generating and persisting post-hoc outputs from trained models.
Heatmaps¶
- class pathforge.inference.heatmaps.InferenceHeatmapResult[source]¶
Bases:
objectSummary of a heatmap produced during inference.
- Variables:
artifact_path (pathlib.Path) – H5 artifact that received the heatmap.
bag_id (str) – Bag id inside the slide artifact, for example
"256px_0.5mpp".heatmap_name (str) – Prediction heatmap namespace.
num_points (int) – Number of unmasked score/coordinate pairs persisted.
output_path (pathlib.Path | None) – Optional JSON sidecar path written for downstream tools.
image_output_path (pathlib.Path | None) – Optional PNG visualization path for quick inspection.
smoothed_image_output_path (pathlib.Path | None) – Optional PNG path containing a blurred “cloud” view of the same heatmap.
top_tiles_output_path (pathlib.Path | None) – Optional PNG path containing a top-K tiles table with per-tile scores and coordinates.
- artifact_path: Path¶
- bag_id: str¶
- heatmap_name: str¶
- num_points: int¶
- output_path: Path | None = None¶
- image_output_path: Path | None = None¶
- smoothed_image_output_path: Path | None = None¶
- top_tiles_output_path: Path | None = None¶
- __init__(artifact_path: Path, bag_id: str, heatmap_name: str, num_points: int, output_path: Path | None = None, image_output_path: Path | None = None, smoothed_image_output_path: Path | None = None, top_tiles_output_path: Path | None = None) None¶
- Parameters:
artifact_path (Path)
bag_id (str)
heatmap_name (str)
num_points (int)
output_path (Path | None)
image_output_path (Path | None)
smoothed_image_output_path (Path | None)
top_tiles_output_path (Path | None)
- Return type:
None
- pathforge.inference.heatmaps.create_inference_heatmap(*, artifact_path: str | Path, bag_id: str, scores_path: str | Path, heatmap_backend: str = 'torchmil', heatmap_name: str = 'torchmil', output_path: str | Path | None = None, image_output_path: str | Path | None = None, coords_path: str | Path | None = None, mask_path: str | Path | None = None, model_path: str | Path | None = None, slide_path: str | Path | None = None, colormap: str = 'inferno', tile_alpha: float = 0.65, smoothed_alpha: float = 0.8, smoothing_sigma_scale: float = 0.75, top_k_tiles: int = 10) InferenceHeatmapResult[source]¶
Create and persist an inference heatmap through an explainer registry.
- Parameters:
artifact_path (str | Path) – Slide H5 artifact containing bags/{bag_id}/coords, or receiving the heatmap when coords_path is provided.
bag_id (str) – Bag id whose coordinates align with the prediction scores.
scores_path (str | Path) – .npy, .npz, or JSON file containing one score per instance shaped [N].
heatmap_backend (str) – Explainer backend key. “torchmil” maps to the registry key “torchmil_heatmap”.
heatmap_name (str) – H5 namespace under bags/{bag_id}/predictions/heatmaps/{heatmap_name}.
output_path (str | Path | None) – Optional JSON sidecar path containing coordinates and scores for non-H5 consumers.
image_output_path (str | Path | None) – Optional PNG path containing a tile-aligned heatmap preview for quick visual inspection.
coords_path (str | Path | None) – Optional .npy, .npz, or JSON coordinate file shaped [N, 2]. If omitted, coords are read from the H5 bag coords and the first two columns are used.
mask_path (str | Path | None) – Optional .npy, .npz, or JSON boolean/binary mask shaped [N].
model_path (str | Path | None) – Optional model checkpoint path recorded in heatmap metadata.
slide_path (str | Path | None) – Optional source WSI path used to render full-resolution top-tile previews. When omitted, the renderer falls back to artifact metadata when available.
colormap (str) – Matplotlib colormap name for exact and smoothed heatmaps.
tile_alpha (float) – Alpha applied to exact square-tile overlays in
[0, 1].smoothed_alpha (float) – Maximum alpha applied to the smoothed cloud overlay in
[0, 1].smoothing_sigma_scale (float) – Gaussian blur scale relative to the mean tile size in thumbnail pixels.
top_k_tiles (int) – Number of highest-scoring tiles to summarize visually.
- Returns:
Summary of the persisted heatmap.
- Return type:
Example
result = create_inference_heatmap( artifact_path="SLIDE_001.h5", bag_id="256px_0.5mpp", scores_path="attention_scores.npy", heatmap_backend="torchmil", heatmap_name="abmil_attention", ) assert result.num_points > 0
- Raises:
KeyError – If the selected explainer backend is not registered.
ValueError – If score/coordinate shapes are invalid or row counts differ.
RuntimeError – If the selected optional backend is unavailable.
- Parameters:
artifact_path (str | Path)
bag_id (str)
scores_path (str | Path)
heatmap_backend (str)
heatmap_name (str)
output_path (str | Path | None)
image_output_path (str | Path | None)
coords_path (str | Path | None)
mask_path (str | Path | None)
model_path (str | Path | None)
slide_path (str | Path | None)
colormap (str)
tile_alpha (float)
smoothed_alpha (float)
smoothing_sigma_scale (float)
top_k_tiles (int)
- Return type:
Model packages¶
- class pathforge.inference.model_package.LoadedModelPackage[source]¶
Bases:
objectSelf-contained packaged PathForge MIL model.
- Variables:
model (pathforge.core.models.mil_base.MILModelBase) – Reconstructed MIL model with weights loaded and set to eval mode.
config (pathforge.config.config.Config) – Validated config required to rebuild the architecture.
package_payload (dict[str, Any]) – Raw serialized package dictionary loaded from disk.
Example
loaded = load_packaged_model("best_model_package.pt") logits = predict_bag(loaded.model, torch.randn(1, 8, 16), task=loaded.task)
- model: MILModelBase¶
- package_payload: dict[str, Any]¶
- property task: str¶
Return the PathForge task name stored in the package metadata.
- property model_name: str¶
Return the registry model name stored in the package metadata.
- property inference_metadata: dict[str, Any]¶
Return packaged feature-selection metadata for inference.
- __init__(model: MILModelBase, config: Config, package_payload: dict[str, Any]) None¶
- Parameters:
model (MILModelBase)
config (Config)
package_payload (dict[str, Any])
- Return type:
None
- pathforge.inference.model_package.save_packaged_model(*, path: str | Path, model: MILModelBase, config: Config, model_name: str, input_dim: int, output_dim: int, checkpoint_path: str | Path | None = None, loss_name: str | None = None) Path[source]¶
Serialize one self-contained inference package to disk.
- Parameters:
path (str | Path) – Output
.ptpath.model (MILModelBase) – Trained MIL model whose weights will be saved.
config (Config) – Active PathForge config used to reconstruct the architecture.
model_name (str) – Registry key used to instantiate the trained model.
input_dim (int) – Instance feature dimension
Dfor bags shaped[B, N, D].output_dim (int) – Number of output channels produced by the model.
checkpoint_path (str | Path | None) – Optional originating Lightning checkpoint path.
loss_name (str | None) – Optional registry loss name for traceability.
- Returns:
Resolved output package path.
- Return type:
Path
- pathforge.inference.model_package.load_packaged_model(path: str | Path, *, map_location: str | device = 'cpu') LoadedModelPackage[source]¶
Load one packaged PathForge MIL model from disk.
- Parameters:
path (str | Path) – Packaged model
.ptpath written bysave_packaged_model().map_location (str | device) – Device mapping used when reading the serialized tensors.
- Returns:
Reconstructed model plus validated config and metadata.
- Return type:
- pathforge.inference.model_package.predict_bag(model: MILModelBase, bag: Tensor, *, task: str, mask: Tensor | None = None, coords: Tensor | None = None) Tensor[source]¶
Run one MIL forward pass and normalize the output tensor.
- Parameters:
model (MILModelBase) – Loaded MIL model.
bag (Tensor) – Feature tensor shaped
[B, N, D].task (str) – PathForge task name controlling output normalization.
mask (Tensor | None) – Optional padding mask shaped
[B, N].coords (Tensor | None) – Optional coordinates shaped
[B, N, 2].
- Returns:
Normalized prediction tensor.
- Return type:
torch.Tensor
- pathforge.inference.model_package.load_bag_from_input(input_path: str | Path, *, bag_id: str | None = None, extractor_name: str | None = None) Tensor[source]¶
Load one feature bag from
.h5,.pt,.npy, or.npzinput.- Parameters:
input_path (str | Path) – Path to one feature artifact.
bag_id (str | None) – Required H5 bag identifier such as
256px_0.5mpp.extractor_name (str | None) – Required H5 extractor key such as
resnet50.
- Returns:
Batched feature tensor shaped
[1, N, D].- Return type:
torch.Tensor
- pathforge.inference.model_package.package_path_from_checkpoint(checkpoint_path: str | Path) Path[source]¶
Return the default packaged-model path next to one Lightning checkpoint.
- Parameters:
checkpoint_path (str | Path)
- Return type:
Path
- pathforge.inference.model_package.select_inference_feature_metadata(package: LoadedModelPackage, *, bag_id: str | None, extractor_name: str | None) tuple[str | None, str | None][source]¶
Resolve bag/extractor selection from CLI overrides or packaged defaults.
- Parameters:
package (LoadedModelPackage)
bag_id (str | None)
extractor_name (str | None)
- Return type:
tuple[str | None, str | None]