Skip to content

feat: add macOS (MPS/CPU) support to training script#240

Open
Ryo722 wants to merge 1 commit into
litagin02:masterfrom
Ryo722:feat/cross-platform-training
Open

feat: add macOS (MPS/CPU) support to training script#240
Ryo722 wants to merge 1 commit into
litagin02:masterfrom
Ryo722:feat/cross-platform-training

Conversation

@Ryo722

@Ryo722 Ryo722 commented Mar 29, 2026

Copy link
Copy Markdown

Summary

Enable train_ms_jp_extra.py to run on macOS with Apple Silicon (MPS) and CPU, while maintaining full CUDA compatibility.

Motivation

The current training script assumes CUDA is always available, which causes crashes on macOS. This PR adds proper device detection and conditional execution so the same script works across CUDA, MPS, and CPU environments.

Changes

  • Device detection: Automatic CUDA > MPS > CPU selection via _DEVICE variable
  • CUDA guards: TF32, SDP, flash attention settings wrapped in torch.cuda.is_available() check
  • Import fallback: torch.cuda.amptorch.amp for PyTorch 2.6+ compatibility
  • DDP backend: gloo on macOS (Darwin) in addition to Windows
  • DDP device_ids: Passed only on CUDA (MPS does not support device_ids)
  • Device transfers: All .cuda(local_rank).to(_DEVICE) with non_blocking preserved for CUDA
  • Safety guards: torch.cuda.set_device() and torch.cuda.empty_cache() guarded

Backward Compatibility

  • CUDA environments: Functionally identical to before. non_blocking=True preserved.
  • No changes to model architecture, training logic, or hyperparameters.

Testing

Tested on macOS 14 (Apple Silicon M4) with PyTorch 2.3 (CPU mode).

Enable training on macOS with Apple Silicon (MPS) and CPU fallback,
while maintaining full CUDA compatibility.

Changes:
- Add device detection: CUDA > MPS > CPU, used throughout the script
- Guard CUDA-specific settings (TF32, SDP, flash attention) behind
  `torch.cuda.is_available()` check
- Add `torch.cuda.amp` import fallback to `torch.amp` for PyTorch 2.6+
- Use gloo DDP backend on macOS (Darwin) in addition to Windows
- Pass `device_ids` to DDP only on CUDA (MPS does not support it)
- Replace all `.cuda(local_rank)` with `.to(_DEVICE)` for portability
- Preserve `non_blocking=True` for CUDA transfers (no-op on CPU/MPS)
- Guard `torch.cuda.set_device()` and `torch.cuda.empty_cache()`
  behind availability checks
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.

1 participant