Skip to content

Add explicit MPS device routing and safe macOS data loading - #237

Open
psgundla wants to merge 4 commits into
mahmoodlab:mainfrom
psgundla:fix/mps-device-69
Open

psgundla wants to merge 4 commits into
mahmoodlab:mainfrom
psgundla:fix/mps-device-69

Conversation

@psgundla

@psgundla psgundla commented Sep 7, 2026 •

Copy link
Copy Markdown

Addresses #69.

The workaround in #69 identifies two obstacles to running TRIDENT on Apple Silicon: CUDA device assumptions and DataLoader multiprocessing. This change adds an explicit CPU/MPS path to both CLIs and keeps MPS data loading in the inference process, without disabling macOS fork-safety checks.

--device mps and --device cpu override the GPU flags and use one slide-processing worker. Omitting --device keeps the existing CUDA and multi-GPU options. Requesting unavailable MPS fails before processing rather than silently falling back to CPU.

The shared WSI loader now uses zero workers for MPS. On macOS, CPU loading tries spawn, then serial loading for readers that cannot be pickled; the serial fallback also sets num_workers=0. Non-pickling inference errors still propagate. Artifact-removal calls receive the execution device instead of relying on their CUDA default.

For a first run:

python run_single_slide.py \
  --slide_path ./wsis/example.svs --job_dir ./trident_mps \
  --device mps --segmenter otsu --patch_encoder resnet50 \
  --mag 20 --patch_size 256

Otsu stays on CPU; patch features use MPS. The batch CLI accepts the same device options. With batch Otsu segmentation, tissue segmentation stays on CPU and the additional artifact-removal model uses the selected execution device.

Artifact removal now uses the selected segmentation batch size instead of its previous default of 16. In the batch CLI, this can increase CUDA memory use; --seg_batch_size can be used to reduce it.

Verification

Validation used upstream f3eb7f3 as the unchanged baseline.

  • 11 new test methods cover CLI device selection, unavailable MPS, device propagation, macOS context selection, real zero-worker fallback, inference-error propagation and rejection of known FlashAttention-only slide encoders. These are mocked unit regressions, separate from the real-data checks below.
  • Local suite: 85 passed, 74 skipped, no failures/errors. Skipped optional integration/GPU tests are not counted as passes.
  • The new tests fail on the unchanged baseline and pass with this patch.

Run the focused tests from the repository root:

python -m unittest discover -s tests -p 'test_mps_device.py' -v

Real-data checks used the public CC0 CMU-1 slide and its small-region export, with actual pretrained weights:

Check Result
Small region, CPU versus MPS, Otsu + ResNet50, both CLIs 58 × 1,024 finite features; identical coordinates; maximum CPU/MPS difference 1.59e-6
Small region, CPU versus MPS, GrandQC tissue/artifact models + Lunit DINO 81 × 384 finite features; identical coordinates; final-mask IoU 1.0; embedding relative L2 difference 4.44e-6
Full three-level WSI on MPS, GrandQC tissue/artifact models + Lunit DINO All 6,051 selected patches processed; 6,051 × 384 finite features; saved coordinates match feature-file coordinates
Small region on RTX A6000, unchanged baseline versus patch, both CLIs All four pipelines completed; feature and coordinate arrays byte-identical per CLI; final masks identical

The full slide is 46,000 × 32,914 pixels at 0.499 µm/pixel, with three stored pyramid levels. Lunit features used 224px patches at 20×; GrandQC tissue and artifact models used their own 1× and 10× targets. The small export and full slide are not independent biological samples.

Weights: Lunit DINO snapshot and GrandQC checkpoint snapshot. No datasets or weights are included in the patch.

MPS runs used an Apple M5, PyTorch 2.14.0 and timm 1.0.29, without PYTORCH_ENABLE_MPS_FALLBACK. CUDA runs used PyTorch 2.7.1+cu128 and the same timm version. The CUDA comparison applied predeclared rtol=1e-5, atol=1e-5 and relative L2 ≤ 1e-5 gates; the measured difference was zero. CPU/MPS differences are numerical smoke checks, not biological equivalence claims.

Limitations and related work

This change focuses on device routing and data loading, rather than making every TRIDENT encoder work on MPS. The batch CLI now gives a clear error for GigaPath, GigaPath-Flash and PRISM2 slide encoders, which require FlashAttention. Other encoders may still run into model-specific operator or precision limitations. Testing did not cover the HEST segmenter, cached workflows, multi-GPU runs or slide-level models.

The single-slide CUDA runs showed the same worker-count and non-writable NumPy-array warnings with and without this patch. Both runs completed successfully, but those warnings remain separate issues. The validation checks that the tested pipelines run and preserve their outputs; it does not assess downstream accuracy or establish a general performance benchmark.

This also leaves the torch.device conversion fix in #108 separate. PR #85 changes the inference interface and touches some of the same loader code, so the changes may need reconciling if it lands first. The experiments shared in #69 provided the starting point for this smaller change, without introducing another inference interface.

@rusparrish

Copy link
Copy Markdown

Confirming the artifact-removal part of this on current main (c07bf25): run_segmentation_job(..., artifact_remover_model=..., device='mps') segments tissue on MPS with HEST, then stops on the artifact step with AssertionError: Torch not compiled with CUDA enabled, since that segment_tissue call falls back to device='cuda:0'. Supplying the device to that call (we patched the default at run time; we haven't run this branch) lets the run finish.

One small addition that might fit here: the same call also doesn't receive batch_size, so the artifact step always runs at the segment_tissue default of 16, whatever --batch_size / --seg_batch_size is set to.

Rus Parrish, Parallax Metrology (github.com/parallaxmetrology)

@psgundla

Copy link
Copy Markdown
Author

Hi @rusparrish, thanks for testing this and confirming the artifact-removal issue on MPS!

Good catch on the batch size too. I’ve pushed a fix to pass the selected segmentation batch size to the artifact-removal step.

I tested it on my Apple Silicon Mac using the CMU-1 small slide region, with GrandQC tissue segmentation and artifact removal on MPS. With a batch size of 1, the artifact model processed six batches of one; with a batch size of 3, it processed two batches of three. The final tissue polygons matched between both runs.

I also checked on CPU that the batch CLI uses --batch_size when --seg_batch_size isn’t set.

@rusparrish

Copy link
Copy Markdown

Thanks for adding the batch size. We ran this branch (0af2d1a) from the CLI on Apple Silicon:

python run_batch_of_slides.py --task seg --wsi_dir ... --job_dir ... --segmenter hest --remove_artifacts --device mps --batch_size 64

It finished on MPS with no CUDA error, on four whole-slide scans (two sections, each scanned on an Aperio AT2 and a GT450). The tissue regions are identical to the ones from our earlier run on c07bf25, where we patched the device in at run time and the artifact step used the default batch size of 16: zero symmetric difference on all four.

Rus Parrish, Parallax Metrology (github.com/parallaxmetrology)

@psgundla

Copy link
Copy Markdown
Author

Thanks for testing the branch on real slides, @rusparrish! Great to hear it ran on MPS without the CUDA error.

@psgundla

Copy link
Copy Markdown
Author

Sorry, I missed the merge conflict earlier. I’ve updated the branch with the latest changes from main and resolved the conflict, keeping both the new TissueQC tests and the batch-size test.

I also updated the MPS test mock for the new detects_artifacts setting.

After the merge, I tested GrandQC tissue segmentation and artifact removal on MPS using the CMU-1 small slide region. Batch sizes of 1 and 3 both completed, and the final tissue polygons matched each other and the result from before the merge.

@guillaumejaume guillaumejaume left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this. I checked out the branch and tested it on Linux (no MPS here):

  • tests/test_mps_device.py and tests/test_run_batch_of_slides.py: 23 passed. Full suite: 125 passed, 79 skipped.
  • run_single_slide.py end to end on a real slide (Otsu + ResNet50, 20x, 256px, 10,462 patches):
    • main (fa1dbee) on CUDA vs. this branch on CUDA: features and coords byte-identical.
    • this branch with --device cpu vs. CUDA: identical coords, max abs feature difference 1.2e-3 (relative L2 4.5e-4), which is expected CPU vs. GPU drift.

The CUDA path looks unchanged and the device routing is clean. Inline comments below: one bug in the batch CLI, one undocumented behavior change on the CUDA path, and a small hardening.

Minor points, no change strictly required:

  • With --segmenter otsu --remove_artifacts --device mps, the single-slide CLI runs GrandQC artifact removal on MPS, while the batch CLI runs it on CPU (it reuses the Otsu seg device). Passing the execution device to the artifact remover in the batch path would make the two CLIs consistent.
  • --device cpu sets gpus = [-1], so it cannot be combined with --gpus -1 -1 for parallel CPU workers. This is documented in the help text, so fine if intended.
  • The final single-process fallback now forces num_workers=0 on Linux too (before, it kept workers with the default context). It is only reached after both fork and spawn hit pickling errors, so low risk.

Comment thread run_batch_of_slides.py Outdated
parser.error('MPS is not available. Use --device cpu or a PyTorch build and Mac with MPS support.')
if args.device is not None:
args.gpus = [-1]
return args

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This early return skips the slide encoder normalization below, so args.patch_encoder is not updated from --slide_encoder when --device is set. For example, --slide_encoder mean-uni_v1 gives patch_encoder=uni_v1 without --device but conch_v15 with --device cpu. Feature extraction is unaffected (Processor derives the patch encoder itself), but the run manifest and summary.md record the wrong encoder, which is what that block exists to prevent.

Suggest setting args.gpus = [-1] and keeping args.device without returning, then skipping only the gpus/device normalization, so the slide encoder block still runs.

Comment thread trident/Processor.py
gdf_saveto = wsi.segment_tissue(
segmentation_model=artifact_remover_model,
target_mag=artifact_remover_model.target_mag,
batch_size=batch_size,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This changes behavior on the CUDA path and is not mentioned in the description. Before, GrandQC artifact removal used the segment_tissue default batch size of 16. Now it uses the segmentation batch size, which in the batch CLI is --batch_size (default 64) unless --seg_batch_size is set. So --remove_artifacts on CUDA now runs the artifact model with a 4x larger batch and more GPU memory.

It may well be the right fix, but it is unrelated to MPS and the byte-identical CUDA check did not cover artifact removal. Could you either mention it in the description or move it (together with test_segmentation_batch_size_override_and_default) to a separate PR?

Comment thread trident/wsi_objects/WSI.py Outdated
def _dataloader_context_candidates(num_workers: int):
if not num_workers or num_workers <= 0:
def _dataloader_context_candidates(num_workers: int, device: str = 'cpu'):
if not num_workers or num_workers <= 0 or device == 'mps':

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

device == 'mps' only matches the exact string. 'mps:0' and torch.device('mps') both fail it (torch.device('mps') == 'mps' is False). The CLIs always pass the plain string, so this only affects library callers, and on macOS they would still get spawn rather than fork. torch.device(device).type == 'mps' would be more robust, and matches what _collect_features already does for autocast.

Comment thread run_batch_of_slides.py Outdated
batch_limit=args.feat_batch_size if args.feat_batch_size is not None else args.batch_size,
)
else:
if device == 'mps' and args.slide_encoder in {'gigapath', 'gigapath-flash', 'prism2'}:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this FlashAttention blocklist will drift as slide encoders are added. Would it fit better as an attribute on the encoder (or in the slide encoder registry), so the check lives next to the model definitions?

@psgundla

Copy link
Copy Markdown
Author

Thanks for the detailed review and for testing the branch on Linux!

I’ve pushed fixes for the slide-encoder metadata and MPS device handling, and moved the FlashAttention requirement to the encoder classes. I also updated the description about artifact batch size and CUDA memory use.

For Otsu, the batch CLI now keeps tissue segmentation on CPU and runs artifact removal on the selected device. I tested this on MPS and CUDA using the CMU-1 example and TCGA-02-0001-01C-01-BS1.svs. Both completed; CUDA results across batch sizes were highly similar, though not identical.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants