You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If device=cpu, I can load pre-trained gpt-2-small on my macbook air and generate from it,
but if device=mps , the pre-trained model gives garbage samples.
Thanks for reporting. Yeah, the mps device can be a bit unstable. I had mixed experiences with it, which is why I didn't recommend it in the main chapters.
I originally started writing the book in PyTorch 2.0, where it was extremely unstable (diverging loss where it would be fine on cpu and cuda). It got a lot better in more recent PyTorch versions, and it was even fine to pre-train it in 2.5 and newer. Fine-tuning remained always flaky, though. Many readers reported the same issue. E.g. one of the more recent discussions related to this: #625
Regarding the pre-trained weights, you are right, they are indeed causing issues on mps devices. For the "Every effort moves" prompt, I am currently getting the following in PyTorch 2.8:
cpu:
Every effort moves you toward the ultimate goal. It's important not to take shortcuts, but not to take shortcuts that only benefit those most at the...
cuda:
Every effort moves you as far as the eye can see. (That's because you're only going to see it at those locations where you know...
mps:
Every effort moves you Psychological vapeween Psychological Hover】 Chev】 vol variedwecotweenut varied Preferencesweenwe Preferences betweenwe Preferencesweenival Galile...
I am not sure yet what causes it. E.g., other LLMs I implemented from scratch in similar fashion (like Qwen3 here, are less sensitive to mps devices choices).
Regarding the generation, I found the culprit :). The issue does not occur when using the generate_text_simple function from chapter 4. Both cpu and mps give identical results.
So it must be something related to the generate function in chapter 5, like some floating point-related rounding on different devices when doing the temperature scaling. I think I know what to try...
Ie a good old log-sum-exp-related trick did the work, since mps maybe had stability issues with exponentiating large logits wheres CPU was fine. If you add the line
that should do the trick. The updated function is:
defgenerate(model, idx, max_new_tokens, context_size, temperature=0.0, top_k=None, eos_id=None):
# For-loop is the same as before: Get logits, and only focus on last time stepfor_inrange(max_new_tokens):
idx_cond=idx[:, -context_size:]
withtorch.no_grad():
logits=model(idx_cond)
logits=logits[:, -1, :]
# New: Filter logits with top_k samplingiftop_kisnotNone:
# Keep only top_k valuestop_logits, _=torch.topk(logits, top_k)
min_val=top_logits[:, -1]
logits=torch.where(logits<min_val, torch.tensor(float('-inf')).to(logits.device), logits)
# New: Apply temperature scalingiftemperature>0.0:
logits=logits/temperature################################################################## New (not in book): numerical stability tip to get equivalent results on mps device# subtract rowwise max before softmaxlogits=logits-logits.max(dim=-1, keepdim=True).values################################################################### Apply softmax to get probabilitiesprobs=torch.softmax(logits, dim=-1) # (batch_size, context_len)# Sample from the distributionidx_next=torch.multinomial(probs, num_samples=1) # (batch_size, 1)# Otherwise same as before: get idx of the vocab entry with the highest logits valueelse:
idx_next=torch.argmax(logits, dim=-1, keepdim=True) # (batch_size, 1)ifidx_next==eos_id: # Stop generating early if end-of-sequence token is encountered and eos_id is specifiedbreak# Same as before: append sampled index to the running sequenceidx=torch.cat((idx, idx_next), dim=1) # (batch_size, num_tokens+1)returnidx
Alternatively, I could have replaced the softmax by
torch.log_softmax(logits, dim=-1)
to the same effect. In hindsight not sure why I didn't. Actually good that you brought that up, otherwise I wouldn't have noticed this issue.
Reacted by Jeroen Van Goey, Abhinav Misra and Atul Acharya
Unfortunately this fix seems insufficient, at least on macbook air m4. I am using the new code for generate, as above (I did a fresh git clone), but when running the last cell in ch05.ipynb (which uses gpt2 weights), I get this nonsense with device=mps (even though it works with device=cpu)
Every effort moves you Haas JaguarvernmentvernmentocenerousVolcompanrepreevaitz Gap Quarterly Sectrous VR Rift vol)),veredcompaninesiana)),
Arg, I remember intermittently testing/comparing to the generate_text_simple function, and maybe I made a mistake and didn't save the script before rerunning and thus got a false positive there. Unfortunately, that's one of the things I can't test via the CI, which could have caught this (or maybe it's now possible if GitHub upgraded the workers).
Hey @rasbt! First off, thanks so much for putting together such an amazing resource! I have had such a good time going through it.
I just wanted to quickly report similar behavior with MPS (even when pulling in the change from this PR). Here is a snapshot of the different training progress on each device.
CPU
Ep 1 (Step 000000): Train loss 2.153, Val loss 2.392
Ep 1 (Step 000050): Train loss 0.617, Val loss 0.637
Ep 1 (Step 000100): Train loss 0.523, Val loss 0.557
Training accuracy: 70.00% | Validation accuracy: 72.50%
Ep 2 (Step 000150): Train loss 0.561, Val loss 0.489
Ep 2 (Step 000200): Train loss 0.419, Val loss 0.397
Ep 2 (Step 000250): Train loss 0.409, Val loss 0.353
Training accuracy: 82.50% | Validation accuracy: 85.00%
Ep 3 (Step 000300): Train loss 0.333, Val loss 0.320
Ep 3 (Step 000350): Train loss 0.340, Val loss 0.306
Training accuracy: 90.00% | Validation accuracy: 90.00%
Ep 4 (Step 000400): Train loss 0.136, Val loss 0.200
Ep 4 (Step 000450): Train loss 0.153, Val loss 0.132
Ep 4 (Step 000500): Train loss 0.222, Val loss 0.137
Training accuracy: 100.00% | Validation accuracy: 97.50%
Ep 5 (Step 000550): Train loss 0.207, Val loss 0.143
Ep 5 (Step 000600): Train loss 0.083, Val loss 0.074
Training accuracy: 100.00% | Validation accuracy: 97.50%
Training completed in 3.10 minutes.
MPS
Ep 1 (Step 000000): Train loss 0.669, Val loss 0.727
Ep 1 (Step 000050): Train loss 0.511, Val loss 0.598
Ep 1 (Step 000100): Train loss 0.500, Val loss 0.542
Training accuracy: 75.00% | Validation accuracy: 80.00%
Ep 2 (Step 000150): Train loss 0.529, Val loss 0.496
Ep 2 (Step 000200): Train loss 0.471, Val loss 0.457
Ep 2 (Step 000250): Train loss 0.400, Val loss 0.433
Training accuracy: 75.00% | Validation accuracy: 85.00%
Ep 3 (Step 000300): Train loss 0.385, Val loss 0.410
Ep 3 (Step 000350): Train loss 0.391, Val loss 0.398
Training accuracy: 87.50% | Validation accuracy: 87.50%
Ep 4 (Step 000400): Train loss 0.252, Val loss 0.405
Ep 4 (Step 000450): Train loss 0.413, Val loss 0.371
Ep 4 (Step 000500): Train loss 0.377, Val loss 0.362
Training accuracy: 90.00% | Validation accuracy: 87.50%
Ep 5 (Step 000550): Train loss 0.365, Val loss 0.357
Ep 5 (Step 000600): Train loss 0.415, Val loss 0.342
Training accuracy: 90.00% | Validation accuracy: 85.00%
Training completed in 0.89 minutes.
Regarding the training behavior, this is unfortunately expected as MPS support in PyTorch is not as mature yet. This is why I didn't recommend it in the main chapters. There was a similar discussion here too: #625
It did get better in recent months though (in earlier versions of PyTorch 2.x it didn't even converge at all). So, I am hopeful that it will improve in upcoming releases.
@wandergeek, I assume you got these results with the 6.7 Finetuning the model on supervised data code in chapter 6.
Ep 5 (Step 000600): Train loss 0.415, Val loss 0.342
Training accuracy: 90.00% | Validation accuracy: 85.00%
Training completed in 0.89 minutes.
I wanted to try out again that code on my MacBook Pro.
But I had much hassle with my conda (condo-forge channel) environment where I could either have PyTorch 2.8.0 and no Tensorflow or Tensorflow and PyTorch 2.6. After a lot trial and error I finally did set up a new uv environment.
By chance it came with PyTorch 2.9.0.
And now I get:
Ep 1 (Step 000000): Train loss 2.153, Val loss 2.392
Ep 1 (Step 000050): Train loss 0.617, Val loss 0.637
Ep 1 (Step 000100): Train loss 0.523, Val loss 0.557
Training accuracy: 70.00% | Validation accuracy: 72.50%
Ep 2 (Step 000150): Train loss 0.561, Val loss 0.489
Ep 2 (Step 000200): Train loss 0.419, Val loss 0.397
Ep 2 (Step 000250): Train loss 0.409, Val loss 0.353
Training accuracy: 82.50% | Validation accuracy: 85.00%
Ep 3 (Step 000300): Train loss 0.333, Val loss 0.320
Ep 3 (Step 000350): Train loss 0.340, Val loss 0.306
Training accuracy: 90.00% | Validation accuracy: 90.00%
Ep 4 (Step 000400): Train loss 0.136, Val loss 0.200
Ep 4 (Step 000450): Train loss 0.153, Val loss 0.132
Ep 4 (Step 000500): Train loss 0.222, Val loss 0.137
Training accuracy: 100.00% | Validation accuracy: 97.50%
Ep 5 (Step 000550): Train loss 0.207, Val loss 0.143
Ep 5 (Step 000600): Train loss 0.083, Val loss 0.074
Training accuracy: 100.00% | Validation accuracy: 97.50%
Training completed in 0.58 minutes.
Run on device: mps
Seems to be fast and precise!
Are the MPS problems with 2.9.x gone now?
@gsgxnet Nice, thanks for sharing. I also just tested chapter 7 in PyTorch 2.9, and it works fine now too on mps devices. I will update the notebooks to automatically use mps when available, if the user has 2.9 installed.
Activity
murphyk commentedon Sep 27, 2025
Similarly, in ch 6, when fine tuning using MPS, results are much worse than when fine tuning with CPU.
(The latter matches your book.)
rasbt commentedon Sep 27, 2025
Thanks for reporting. Yeah, the mps device can be a bit unstable. I had mixed experiences with it, which is why I didn't recommend it in the main chapters.
I originally started writing the book in PyTorch 2.0, where it was extremely unstable (diverging loss where it would be fine on cpu and cuda). It got a lot better in more recent PyTorch versions, and it was even fine to pre-train it in 2.5 and newer. Fine-tuning remained always flaky, though. Many readers reported the same issue. E.g. one of the more recent discussions related to this: #625
Regarding the pre-trained weights, you are right, they are indeed causing issues on mps devices. For the "Every effort moves" prompt, I am currently getting the following in PyTorch 2.8:
cpu:
cuda:
mps:
I am not sure yet what causes it. E.g., other LLMs I implemented from scratch in similar fashion (like Qwen3 here, are less sensitive to mps devices choices).
murphyk commentedon Sep 27, 2025
Yes, in mps (on my macbook m4) I get
it's a shame it doesn't work, since mps is 2x faster than cpu :)
rasbt commentedon Sep 27, 2025
Regarding the generation, I found the culprit :). The issue does not occur when using the
generate_text_simplefunction from chapter 4. Both cpu and mps give identical results.So it must be something related to the
generatefunction in chapter 5, like some floating point-related rounding on different devices when doing the temperature scaling. I think I know what to try...rasbt commentedon Sep 27, 2025
I think I found and fixed it via #849.
Ie a good old log-sum-exp-related trick did the work, since mps maybe had stability issues with exponentiating large logits wheres CPU was fine. If you add the line
before the
that should do the trick. The updated function is:
Alternatively, I could have replaced the softmax by
to the same effect. In hindsight not sure why I didn't. Actually good that you brought that up, otherwise I wouldn't have noticed this issue.
murphyk commentedon Sep 27, 2025
murphyk commentedon Sep 27, 2025
Unfortunately this fix seems insufficient, at least on macbook air m4. I am using the new code for
generate, as above (I did a fresh git clone), but when running the last cell in ch05.ipynb (which uses gpt2 weights), I get this nonsense with device=mps (even though it works with device=cpu)Full code:
rasbt commentedon Sep 27, 2025
Arg, I remember intermittently testing/comparing to the
generate_text_simplefunction, and maybe I made a mistake and didn't save the script before rerunning and thus got a false positive there. Unfortunately, that's one of the things I can't test via the CI, which could have caught this (or maybe it's now possible if GitHub upgraded the workers).Will investigate more in the next days.
wandergeek commentedon Oct 14, 2025
Hey @rasbt! First off, thanks so much for putting together such an amazing resource! I have had such a good time going through it.
I just wanted to quickly report similar behavior with MPS (even when pulling in the change from this PR). Here is a snapshot of the different training progress on each device.
CPU
MPS
rasbt commentedon Oct 14, 2025
Thanks for the feedback @wandergeek
Regarding the training behavior, this is unfortunately expected as MPS support in PyTorch is not as mature yet. This is why I didn't recommend it in the main chapters. There was a similar discussion here too: #625
It did get better in recent months though (in earlier versions of PyTorch 2.x it didn't even converge at all). So, I am hopeful that it will improve in upcoming releases.
gsgxnet commentedon Oct 27, 2025
@wandergeek, I assume you got these results with the 6.7 Finetuning the model on supervised data code in chapter 6.
I wanted to try out again that code on my MacBook Pro.
But I had much hassle with my
conda(condo-forge channel) environment where I could either have PyTorch 2.8.0 and no Tensorflow or Tensorflow and PyTorch 2.6. After a lot trial and error I finally did set up a newuvenvironment.By chance it came with PyTorch 2.9.0.
And now I get:
Seems to be fast and precise!
Are the MPS problems with 2.9.x gone now?
rasbt commentedon Nov 1, 2025
@gsgxnet Nice, thanks for sharing. I also just tested chapter 7 in PyTorch 2.9, and it works fine now too on mps devices. I will update the notebooks to automatically use mps when available, if the user has 2.9 installed.
rasbt commentedon Nov 1, 2025
I was just testing the
generatefunction, and while the results are different in mps, it now is at least sensible:"mps":
So I am closing this as hopefully resolved.