Skip to content

Retire the MPS generate_from_raw warning: the PyTorch bug it references was fixed in torch 2.9.0 #1739

Closed

Description

@planetf1

Impact

Anyone batching prompts through generate_from_raw on Apple Silicon sees this on every call:

utilizing device mps with a `generate_from_raw` request; you may see issues when
submitting batches of prompts to a Hugging Face backend; ensure all ModelOutputThunks
have non-empty values.

The warning tells users their results may be numerically broken, links a PyTorch PR that shows as closed and unmerged, and asks them to verify something that fails on healthy stacks. So people go hunting for NaNs that are not there, or steer clear of MPS and batching to be safe. Both premises behind the warning had already stopped holding when it was written: the PyTorch bug was fixed in torch 2.9.0 (October 2025), and an empty output in a batch is often just the model emitting end-of-text on its first token.

The warning

mellea/backends/huggingface.py:2597-2603 on main (2332-2338 on v0.8.0), added in bbddd0eaf5 on 2026-06-10. The guard checks only the device, so it fires on every raw call on MPS, batch or not. Its TODO reads:

# TODO: Remove this when we are able to update the torch package.
#       Test this by ensuring all outputs from this call are populated when running on mps.
#       https://github.com/pytorch/pytorch/pull/157727

History of the PyTorch fix

  • 2025-06-24: MPS SDPA returns NaN when attention mask blocks all rows pytorch/pytorch#156707 filed, "MPS SDPA returns NaN when attention mask blocks all rows". Root cause in aten/src/ATen/native/mps/operations/Attention.mm: Metal's softmax on an all--inf row yields NaN, while CPU returns zeros explicitly. Hit by left-padded batched generation in HF transformers.
  • 2025-07-07: Address NaNs if SDPA is called with all values masked from query pytorch/pytorch#157727 opened. Zero the outputs where every softmax input is -inf, aligning MPS with CPU: +15/-1 in Attention.mm, plus a test.
  • 2025-07-11: approved by a maintainer, with a question about performance; the author benchmarked on an M2 Max and the cost disappeared into measurement noise at realistic sizes.
  • 2025-07-14: merge commanded. PyTorch's mergebot committed the change straight to main as 194539e9c (author jhavukainen, committer pytorchmergebot) and closed the PR without a GitHub merge, so the PR still reads closed and unmerged even though the change is in. The issue closed the same evening.
  • The fix first shipped in torch 2.9.0, released 2025-10-15. Verified directly: v2.8.0 does not contain the commit, v2.9.0 does.

The mellea warning went in on 2026-06-10, eight months after 2.9.0. By then every torch release users install carried the fix, and the TODO's own removal condition ("when we are able to update the torch package") had long been met.

What I tested

mellea 0.8.0 from PyPI (clean resolution), torch 2.14.1, transformers 5.17.0, peft 0.21.2, Python 3.14.8, Apple M4 Max, MPS.

  • Batched 3-prompt generate_from_raw against granite-4.0-micro: one thunk comes back empty, same row every time across repeated runs.
  • The identical batch on CPU (via custom_config): the same row is empty. Device-independent.
  • Token inspection of the empty row: it generates [<|end_of_text|>, <|pad|>, <|pad|>, ...], first-token EOS then pad fill, which decodes to "" with special tokens skipped. Ordinary model behaviour on a raw, untemplated prompt.
  • Op-level probe of the exact scenario #156707 describes (attention rows fully masked): scaled_dot_product_attention returns zeros on MPS in torch 2.14.1, matching CPU, in fp32 and bf16, with additive and boolean masks. The NaN does not reproduce.

Reproducer

import asyncio
from mellea.backends.huggingface import LocalHFBackend
from mellea.backends.model_ids import IBM_GRANITE_4_MICRO_3B
from mellea.stdlib.components import CBlock, Message
from mellea.stdlib.context import ChatContext

hf = LocalHFBackend(model_id=IBM_GRANITE_4_MICRO_3B)
ctx = ChatContext().add(Message("user", "Answer briefly."))
results = asyncio.run(hf.generate_from_raw(
    [
        CBlock(value="Say hello."),
        CBlock(value="Say goodbye now."),  # empty thunk, every run
        CBlock(value="Count from one to five using digits separated by spaces."),
    ],
    ctx,
))
print([str(r) for r in results])  # row 1: ''
# why row 1 is empty: immediate EOS, then pad fill
enc = tok(prompts, return_tensors="pt", padding=True).to("mps")
out = model.generate(**enc)
tok.decode(out[1][enc["input_ids"].shape[1]:], skip_special_tokens=False)
# '<|end_of_text|><|pad|><|pad|>...'

Why this is a mellea bug

  1. The idea that MPS batched generation is numerically unreliable is false on every torch release mellea supports today (2.9.0 and later).
  2. The prescribed check, "ensure all ModelOutputThunks have non-empty values", can never pass universally: first-token EOS legitimately produces empty thunks on any device.
  3. The TODO's removal condition has been met for about a year, but the linked PR displays as unmerged, so it reads as blocked when it is not.

Suggested change

Drop the warning and its TODO. If a note is still wanted, say plainly that batched raw generation can return empty thunks when the model emits EOS immediately, with no device gate and no PyTorch link. An opt-in caller-side assertion on non-empty results would be the right shape for anyone who needs the guarantee.

No test or doc references the warning text, so the change is self-contained.

Activity

  1. added
    bug
    good first issue
    area/backends
    on Oct 16, 2026
  2. Vamsi-2581 commented on Oct 16, 2026

    @Vamsi-2581

    Hi, I’d like to take this issue. I’ve prepared the scoped change to remove the obsolete MPS-only warning and its TODO from generate_from_raw; it does not change generation behavior. Please assign me if that approach is suitable, and I’ll submit a PR once routed.

  3. planetf1 commented on Oct 16, 2026

    @planetf1
    ContributorAuthor

    Why the non-empty validation stays a caller concern

    The suggested change deliberately removes the warning without replacing it with any non-empty validation on ModelOutputThunk. Three reasons a framework-level guarantee would be the wrong contract:

    1. Empty is a valid model decision. First-token EOS is the model ending its turn, most commonly on the untemplated raw path where the caller controls the prompt. It is also expected for one-token readout adapter functions, where the answer token can decode to an empty string once special tokens are skipped. A non-empty guarantee would turn correct output into a contract violation.

    2. mellea cannot enforce it. It fronts several backends whose models and servers legally emit EOS-first (Ollama, OpenAI, vLLM, local HF). Enforcing non-empty would mean retrying, fabricating content, or raising on legitimate output. In streaming, a thunk is empty by definition until the first token arrives, so the invariant could not hold across the object's lifecycle anyway.

    3. The existing contract boundary is the right one. mellea guarantees shape and fails loud on malformed output: io.yaml contracts, AdapterSchemaMismatchError, ValueError for non-JSON intrinsic output. Content-level policy like "non-empty" belongs to the caller, and the compositional mechanism already exists: express it as a Requirement with a sampling strategy and let instruct-validate-repair handle it.

    So a caller that needs non-empty rows should assert it at the call site or express it as a requirement; the framework keeps reporting what the model actually did.

  4. self-assigned this
    on Oct 16, 2026
  5. added a commit that references this issue on Oct 19, 2026
    a0a17a0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area/backendsbuggood first issue

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions