Skip to content

Build a modern LLM from scratch. Every line commented. Explained like we are five.

MPS after CUDA .. thanks Peter

raiyanyahya725f664810e2
diff --git a/chapters/08_training.md b/chapters/08_training.md
index e13e1fb..7a6cf5f 100644
--- a/chapters/08_training.md
+++ b/chapters/08_training.md
@@ -163,7 +163,7 @@ AdamW update step:
```python
# autocast context: automatically uses bfloat16 where safe
-with torch.cuda.amp.autocast(enabled=use_amp):
+with torch.amp.autocast(device.type, enabled=use_amp):
_, loss = model(input_ids, targets=target_ids)
# scaler handles loss scaling for float16, not needed for bfloat16 on modern GPUs
@@ -391,8 +391,8 @@ def train(model, train_dataset, config, device, save_dir="checkpoints"):
max_steps=config.max_steps, max_lr=config.learning_rate,
)
- use_amp = device.type == "cuda"
- scaler = torch.cuda.amp.GradScaler(enabled=use_amp) if use_amp else None
+ use_amp = device.type != "cpu"
+ scaler = torch.amp.GradScaler(device.type, enabled=use_amp) if use_amp else None
step = 0
total_loss = 0.0
@@ -414,7 +414,7 @@ def train(model, train_dataset, config, device, save_dir="checkpoints"):
target_ids = target_ids.to(device, non_blocking=True)
# ===== FORWARD: Predict next tokens, measure error =====
- with torch.cuda.amp.autocast(enabled=use_amp):
+ with torch.amp.autocast(device.type, enabled=use_amp):
_, loss = model(input_ids, targets=target_ids)
loss = loss / config.grad_accum_steps
diff --git a/main.py b/main.py
index d9fe9ac..65f3bdf 100644
--- a/main.py
+++ b/main.py
@@ -11,6 +11,18 @@ from datasets import load_dataset
import matplotlib.pyplot as plt
+# ===== DEVICE SELECTION =====
+def find_device():
+ if torch.cuda.is_available():
+ print(f"GPU: {torch.cuda.get_device_name(0)}")
+ return torch.device("cuda")
+ if torch.mps.is_available():
+ print("Using Apple MPS")
+ return torch.device("mps")
+ print("Using CPU")
+ return torch.device("cpu")
+
+
# ===== ROTARY POSITION EMBEDDINGS (RoPE) =====
class RotaryPositionalEmbedding(nn.Module):
def __init__(self, d_model, max_seq_len=2048, theta=10000.0):
@@ -313,8 +325,8 @@ def train(model, train_dataset, config, device, steps=500):
optimizer = create_optimizer(model, config)
scheduler = CosineWarmupScheduler(optimizer, config.warmup_steps,
steps, max_lr=config.learning_rate)
- use_amp = device.type == 'cuda'
- scaler = torch.amp.GradScaler('cuda', enabled=use_amp) if use_amp else None
+ use_amp = device.type != 'cpu'
+ scaler = torch.amp.GradScaler(device.type, enabled=use_amp) if use_amp else None
step = 0
loss_history = []
start = time.time()
@@ -325,7 +337,7 @@ def train(model, train_dataset, config, device, steps=500):
break
input_ids = input_ids.to(device)
target_ids = target_ids.to(device)
- with torch.amp.autocast('cuda', enabled=use_amp):
+ with torch.amp.autocast(device.type, enabled=use_amp):
_, loss = model(input_ids, target_ids)
loss = loss / config.grad_accum_steps
if scaler:
@@ -384,12 +396,7 @@ def main():
# warmup_steps=2000, learning_rate=3e-4,
# )
- if torch.cuda.is_available():
- device = torch.device("cuda")
- print(f"GPU: {torch.cuda.get_device_name(0)}")
- else:
- device = torch.device("cpu")
- print("Using CPU")
+ device = find_device()
tokenizer = SimpleTokenizer()
print("Loading training data...")