Repository navigation
Conversation
|
Confirming the artifact-removal part of this on current main (c07bf25): One small addition that might fit here: the same call also doesn't receive Rus Parrish, Parallax Metrology (github.com/parallaxmetrology) |
|
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 |
|
Thanks for adding the batch size. We ran this branch (0af2d1a) from the CLI on Apple Silicon:
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) |
|
Thanks for testing the branch on real slides, @rusparrish! Great to hear it ran on MPS without the CUDA error. |
|
Sorry, I missed the merge conflict earlier. I’ve updated the branch with the latest changes from I also updated the MPS test mock for the new 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
left a comment
There was a problem hiding this comment.
Thanks for this. I checked out the branch and tested it on Linux (no MPS here):
tests/test_mps_device.pyandtests/test_run_batch_of_slides.py: 23 passed. Full suite: 125 passed, 79 skipped.run_single_slide.pyend 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 cpuvs. 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 cpusetsgpus = [-1], so it cannot be combined with--gpus -1 -1for parallel CPU workers. This is documented in the help text, so fine if intended.- The final single-process fallback now forces
num_workers=0on 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.
| 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 |
There was a problem hiding this comment.
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.
| gdf_saveto = wsi.segment_tissue( | ||
| segmentation_model=artifact_remover_model, | ||
| target_mag=artifact_remover_model.target_mag, | ||
| batch_size=batch_size, |
There was a problem hiding this comment.
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?
| 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': |
There was a problem hiding this comment.
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.
| 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'}: |
There was a problem hiding this comment.
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?
|
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 |
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 mpsand--device cpuoverride the GPU flags and use one slide-processing worker. Omitting--devicekeeps 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 setsnum_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:
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_sizecan be used to reduce it.Verification
Validation used upstream f3eb7f3 as the unchanged baseline.
Run the focused tests from the repository root:
python -m unittest discover -s tests -p 'test_mps_device.py' -vReal-data checks used the public CC0 CMU-1 slide and its small-region export, with actual pretrained weights:
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 predeclaredrtol=1e-5,atol=1e-5and 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.deviceconversion 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.