Skip to content

sec 5.5: loading gpt-2-small weights onto MPS gives nonsense #846

Closed

Description

@murphyk

Bug description

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.

Image

What operating system are you using?

macOS

Where do you run your code?

Local (laptop, desktop)

Environment

[OK] Your Python version is 3.10.18
[OK] torch 2.8.0
[OK] jupyterlab 4.4.7
[OK] tiktoken 0.11.0
[OK] matplotlib 3.10.6
[OK] tensorflow 2.20.0
[OK] tqdm 4.67.1
[OK] numpy 2.0.2
[OK] pandas 2.3.2
[OK] psutil 7.1.0



Activity

  1. added
    bug
    on Sep 26, 2025
  2. murphyk commented on Sep 27, 2025

    @murphyk
    Author

    Similarly, in ch 6, when fine tuning using MPS, results are much worse than when fine tuning with CPU.
    (The latter matches your book.)

  3. rasbt commented on Sep 27, 2025

    @rasbt
    Owner

    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).

  4. murphyk commented on Sep 27, 2025

    @murphyk
    Author

    Yes, in mps (on my macbook m4) I get

     Every effort moves you Haas JaguarvernmentvernmentocenerousVolcompanrepreevaitz Gap Quarterly Sectrous VR Rift vol)),veredcompaninesiana)),‎
    

    it's a shame it doesn't work, since mps is 2x faster than cpu :)

  5. rasbt commented on Sep 27, 2025

    @rasbt
    Owner

    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...

  6. rasbt commented on Sep 27, 2025

    @rasbt
    Owner

    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

    logits = logits - logits.max(dim=-1, keepdim=True).values

    before the

    probs = torch.softmax(logits, dim=-1)  # (batch_size, context_len)

    that should do the trick. The updated function is:

    def generate(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 step
        for _ in range(max_new_tokens):
            idx_cond = idx[:, -context_size:]
            with torch.no_grad():
                logits = model(idx_cond)
            logits = logits[:, -1, :]
    
            # New: Filter logits with top_k sampling
            if top_k is not None:
                # Keep only top_k values
                top_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 scaling
            if temperature > 0.0:
                logits = logits / temperature
     
                #################################################################
                # New (not in book): numerical stability tip to get equivalent results on mps device
                # subtract rowwise max before softmax
                logits = logits - logits.max(dim=-1, keepdim=True).values
                ##################################################################
    
                # Apply softmax to get probabilities
                probs = torch.softmax(logits, dim=-1)  # (batch_size, context_len)
    
                # Sample from the distribution
                idx_next = torch.multinomial(probs, num_samples=1)  # (batch_size, 1)
    
            # Otherwise same as before: get idx of the vocab entry with the highest logits value
            else:
                idx_next = torch.argmax(logits, dim=-1, keepdim=True)  # (batch_size, 1)
    
            if idx_next == eos_id:  # Stop generating early if end-of-sequence token is encountered and eos_id is specified
                break
    
            # Same as before: append sampled index to the running sequence
            idx = torch.cat((idx, idx_next), dim=1)  # (batch_size, num_tokens+1)
    
        return idx

    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.

  7. murphyk commented on Sep 27, 2025

    @murphyk
    Author
  8. murphyk commented on Sep 27, 2025

    @murphyk
    Author

    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)),‎
    

    Full code:

    torch.manual_seed(123)
    
    gpt = GPTModel(NEW_CONFIG)
    gpt.eval();
    device = 'mps'
    load_weights_into_gpt(gpt, params)
    gpt.to(device);
    
    token_ids = generate(
        model=gpt,
        idx=text_to_token_ids("Every effort moves you", tokenizer).to(device),
        max_new_tokens=25,
        context_size=NEW_CONFIG["context_length"],
        top_k=50,
        temperature=1.5
    )
    
    print("Output text!:\n", token_ids_to_text(token_ids, tokenizer))
    
  9. rasbt commented on Sep 27, 2025

    @rasbt
    Owner

    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).

    Will investigate more in the next days.

  10. reopened this on Oct 7, 2025
  11. wandergeek commented on Oct 14, 2025

    @wandergeek

    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.
    
  12. rasbt commented on Oct 14, 2025

    @rasbt
    Owner

    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.

  13. gsgxnet commented on Oct 27, 2025

    @gsgxnet

    @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?

  14. rasbt commented on Nov 1, 2025

    @rasbt
    Owner

    @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.

  15. rasbt commented on Nov 1, 2025

    @rasbt
    Owner

    I was just testing the generate function, and while the results are different in mps, it now is at least sensible:

    "mps":

    Every effort moves you toward more efficient and efficient processes, like in the car's oil and gas operation," the study said.

    So I am closing this as hopefully resolved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions