Skip to content

Add Apple M-series (MPS) device support to Python scripts #977

Open

Description

@brianholland

Summary

Most standalone Python scripts (.py) only detect CUDA or fall back to CPU, ignoring Apple Silicon's MPS backend. This means users with M1/M2/M3/M4 Macs always fall back to CPU, missing significant GPU acceleration.

Problem

~29 Python files use this pattern:

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

This should be updated to also detect MPS:

if torch.cuda.is_available():
    device = torch.device("cuda")
elif torch.backends.mps.is_available():
    device = torch.device("mps")
else:
    device = torch.device("cpu")

Additional considerations

  • pin_memory=True in DataLoaders should be conditional on CUDA availability
  • torch.compile should be guarded (limited MPS support)
  • DDP scripts are inherently CUDA-only and should be left as-is

Scope

  • All standalone .py training/inference scripts in ch04-ch07, appendix, and pkg/tests
  • Excludes DDP-specific scripts (appendix-A DDP scripts, ch05/10 multi-GPU)
  • Excludes notebooks (many already have MPS support)

🤖 Generated with Claude Code

Activity

  1. rasbt commented on Mar 9, 2026

    @rasbt
    Owner

    If someone reads this, this omission of mps was on purpose (see #625 #644 #442 #846)

    Perhaps worthwhile revisiting some time in the future though.

  2. amit-chaubey commented on Mar 19, 2026

    @amit-chaubey
    Contributor

    If you use mps

    torch.manual_seed(123)
    model = NeuralNetwork(num_inputs=2, num_outputs=2)
    
    device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")
    model.to(device)
    
    
    optimizer = torch.optim.SGD(model.parameters(), lr=0.5)
    
    num_epochs = 3
    start_time = time.time()
    for epoch in range(num_epochs):
        
        model.train()
        for batch_idx, (features, labels) in enumerate(train_loader):
            features, labels = features.to(device), labels.to(device)
            logits = model(features)
            loss = F.cross_entropy(logits, labels) # Loss function
    
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
    
            ### LOGGING
            print(f"Epoch: {epoch+1:03d}/{num_epochs:03d}"
                  f" | Batch {batch_idx:03d}/{len(train_loader):03d}"
                  f" | Train/Val Loss: {loss:.2f}")
    
    
        model.eval()
    
    end_time = time.time()
    print(f"Time taken: {end_time - start_time} seconds")
    #Time taken: 0.014540672302246094 seconds

    if you use cpu

    torch.manual_seed(123)
    model = NeuralNetwork(num_inputs=2, num_outputs=2)
    
    device = torch.device("cpu")
    model.to(device)
    
    optimizer = torch.optim.SGD(model.parameters(), lr=0.5)
    
    num_epochs = 3
    
    start_time = time.time()
    for epoch in range(num_epochs):
    
        model.train()
        for batch_idx, (features, labels) in enumerate(train_loader):
            features, labels = features.to(device), labels.to(device)
            logits = model(features)
            loss = F.cross_entropy(logits, labels) # Loss function
    
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
    
            ### LOGGING
            print(f"Epoch: {epoch+1:03d}/{num_epochs:03d}"
                  f" | Batch {batch_idx:03d}/{len(train_loader):03d}"
                  f" | Train/Val Loss: {loss:.2f}")
        model.eval()
    end_time = time.time()
    print(f"Time taken: {end_time - start_time} seconds")
    
    #Time taken: 0.0030498504638671875 seconds

    MPS is stuck in no-man's land, too slow for large models, overkill overhead for small ones. i feel its much slower.
    you may use runpod and any other cloud gpu to accelerate training. one of the reason could be Apple unified memory is shared between CPU/GPU.

    Thanks for amazing book @rasbt

  3. kushdab commented on Jun 26, 2026

    @kushdab

    The three-tier pattern is exactly right, and it covers all 29 files cleanly. Two nuances worth handling while you're there:

    1. pin_memory in DataLoaders must be CUDA-conditional
    pin_memory=True is silently ignored (or throws on some builds) when the device isn't CUDA. Safe pattern:

    DataLoader(dataset, pin_memory=(device.type == 'cuda'), ...)

    2. torch.compile falls back or errors on MPS
    Guard any torch.compile(model) call:

    if device.type not in ('mps',):
        model = torch.compile(model)

    As of torch 2.3 MPS compile support is still partial — the compiled path silently falls back to eager mode on many ops, so you only lose startup time, but it's cleaner to skip it.

    3. bfloat16 is not supported on MPS (use float16 instead)
    Any place that does model.to(torch.bfloat16) will crash on Metal. A dtype helper keeps this tidy:

    TRAIN_DTYPE = torch.bfloat16 if device.type == 'cuda' else torch.float16

    Happy to help review the diff once a PR is up.

  4. rasbt commented on Aug 26, 2026

    @rasbt
    Owner

    Just stumbled upon a great investigative write-up on the topic: "Finding a Bug in Closed-Source Shader Kernels", https://scottkirila.studio.site/blog/kernel-bug

  5. mikemikimike commented on Aug 27, 2026

    @mikemikimike
    Contributor

    Implemented in PR #1073.

    • Changed: added a reusable PyTorch device selector with CUDA, Apple MPS, and CPU fallback.
    • Tests: PYTHONPATH=pkg python -m pytest pkg/llms_from_scratch/tests/test_device.py (3 passed).
    • Validation: Ruff and git diff --check passed.
  6. rasbt commented on Sep 30, 2026

    @rasbt
    Owner

    Just as a heads-up I plan on this in Nov/Dec and reevaluate all the code carefully on MPS with the latest PyTorch then and see if MPS can now be safely recommended. In the meantime, please don't worry about it, I'll take care of it then!

  7. self-assigned this
    on Sep 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions