Skip to content

Fix FakeTensor/concrete metadata mismatch for log_sigmoid on MPS - #195417

Open
tgrhn wants to merge 1 commit into
pytorch:mainfrom
tgrhn:fix-logsigmoid-jvp-decomp-mps-buffer
Open

tgrhn wants to merge 1 commit into
pytorch:mainfrom
tgrhn:fix-logsigmoid-jvp-decomp-mps-buffer

Conversation

@tgrhn

@tgrhn tgrhn commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

log_sigmoid_forward's decomposition (used for FakeTensor/meta shape
inference, e.g. under CrossRefFakeMode and torch.compile) only
special-cased CUDA and XPU when deciding the shape of its second,
mostly-unused output (buffer). Those backends get an empty (0,)
buffer, everything else (including MPS) falls through to a full
self-shaped buffer. MPS's native log_sigmoid_forward/log_sigmoid_backward
kernels have always allocated buffer as at::empty({0}, ...) and ignored
its contents, matching CUDA/XPU, not CPU -- so FakeTensor-inferred output
shape for an MPS tensor diverges from what the real kernel produces.

This is the same class of bug already fixed for XPU in #141333, which
touched the same two files (torch/_decomp/decompositions.py and
torch/_decomp/decompositions_for_jvp.py); MPS was never added alongside
XPU at the time. This PR adds self.is_mps to the same condition in both
files.

Why not not self.is_cpu? Meta tensors have is_cpu == False, and this op has no Meta kernel, so the decomposition is what aten.log_sigmoid_forward returns on meta inputs. Meta has to keep the full buffer, and inverting the check would change it to (0,). is_cpu or is_meta doesn't work either: torch_xla returns a full buffer and reads it in backward. The device check can't be generalized inside the decomposition. That needs the dispatch-level approach in #194355.

Test Plan

Reproduced the exact failure mode from the original XPU issue
(#141332), swapped to MPS:

import torch
from torch._subclasses import CrossRefFakeMode
import torch.nn.functional as F

with CrossRefFakeMode():
    input = torch.tensor([1.0, 1.0, 1.0, 1.0, 1.0], device='mps')
    F.logsigmoid(input)
  • Before the fix: raises MetadataMismatchError: ... found mismatched tensor metadata for output[1]: Shapes torch.Size([0]) and torch.Size([5]) are not equal!
  • After the fix: runs cleanly
  • Verified no correctness regression on MPS vs CPU for plain
    forward/backward and forward-mode-AD double backward (which is what
    decompositions_for_jvp.py's version is used for) -- max diffs at
    fp32 precision level (1.19e-07 / 3.73e-09)
  • lintrunner -a on both changed files: clean

`log_sigmoid_forward`'s CompositeImplicitAutograd decomposition (used by
FakeTensor/meta shape inference, e.g. under CrossRefFakeMode and
torch.compile) only special-cased CUDA and XPU when deciding the shape of
its second, mostly-unused output (`buffer`): those backends get an empty
`(0,)` buffer, while every other device -- including CPU, but also MPS --
falls through to the `else` branch and gets a full self-shaped buffer.

The root cause is that MPS's native log_sigmoid_forward/backward kernels
(aten/src/ATen/native/mps/operations/ActivationKernel.mm) have always
allocated `buffer` as `at::empty({0}, ...)` and ignored its contents (same
"buffer is only used by CPU dispatch, we just ignore it here" comment as
CUDA's implementation), going back to when the op was first added for MPS
(pytorch#95280) and unchanged by the later MPSGraph->Metal migration (pytorch#187228).
The decomposition's shape-inference branch never accounted for that, so
FakeTensor-inferred output metadata for an MPS tensor (buffer shape ==
self shape) diverges from what the real MPS kernel produces (buffer shape
== `(0,)`).

This is the same bug class already fixed for XPU in pytorch#141333 ("Fix
mismatched tensor metadata between FakeTensor and Intel XPU concrete
tensor when running F.logsigmoid"), which touched the same two files.
MPS was simply never added alongside XPU at the time. This change adds
`self.is_mps` to the same condition in both `torch/_decomp/decompositions.py`
and `torch/_decomp/decompositions_for_jvp.py` (the latter is the
JIT-registered decomposition used for forward-mode-AD-compatible double
backward, loaded via torch/autograd/forward_ad.py).

Test Plan:

Reproduced the exact failure mode from the original XPU issue
(pytorch#141332), swapped to MPS,
confirmed it errors before the fix and is silent after:

```
python -c "
import torch
from torch._subclasses import CrossRefFakeMode
import torch.nn.functional as F

with CrossRefFakeMode():
    input = torch.tensor([1.0, 1.0, 1.0, 1.0, 1.0], device='mps')
    F.logsigmoid(input)
"
```

Before the fix this raises:
`MetadataMismatchError: ... found mismatched tensor metadata for
output[1]: Shapes torch.Size([0]) and torch.Size([5]) are not equal!`

After the fix it runs cleanly.

Also verified no correctness regression on MPS for both plain forward/backward
and forward-mode-AD double backward (which is what
decompositions_for_jvp.py's version is used for), comparing against CPU:

```
python -c "
import torch
import torch.nn.functional as F
import torch.autograd.forward_ad as fwAD

torch.manual_seed(0)
x_ = torch.randn(8)
gO_ = torch.ones(8)
tangent_ = torch.randn(8)

def full(x, gO):
    y = F.logsigmoid(x)
    gx, = torch.autograd.grad(y, x, gO, create_graph=True)
    return gx

def run(device):
    x = x_.to(device).clone().requires_grad_(True)
    gO = gO_.to(device)
    tangent = tangent_.to(device)
    with fwAD.dual_level():
        dual_x = fwAD.make_dual(x.detach().requires_grad_(True), tangent)
        out = full(dual_x, gO)
        result, jvp = fwAD.unpack_dual(out)
        return result.detach().cpu(), jvp.detach().cpu()

r_cpu, j_cpu = run('cpu')
r_mps, j_mps = run('mps')
print('result max diff', (r_cpu - r_mps).abs().max().item())
print('jvp max diff', (j_cpu - j_mps).abs().max().item())
"
```
Output: `result max diff 1.1920928955078125e-07`, `jvp max diff
3.725290298461914e-09` (fp32-level precision, matches CPU).

Ran `lintrunner -a` on both changed files: clean.
@pytorch-bot

pytorch-bot Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/195417

Note: Links to docs will display an error until the docs builds have been completed.

❌ 2 New Failures, 3 Unclassified Failures

As of commit 3cbbf8d with merge base 33812ec (image):

NEW FAILURES - The following jobs have failed:

  • BC Lint (gh)

    AI verdict: AI verdict: infra issue

    The BC Lint run never ran a job. It has zero jobs and zero check-runs, and it was marked failed exactly 30 days after it was created, at the same second as every other pull_request workflow on this SHA. That is the pattern of runs that sat waiting for approval (the contributor is from outside the org) and expired. The suspect is a 2-line change to a condition inside two Python decomposition function bodies, which cannot plausibly affect BC Lint.

    Full reasoning on HUD →

  • Lint (gh)

    AI verdict: AI verdict: infra issue

    The Lint run for this commit (run 33368330340) has zero jobs. It was created 2026-08-31T07:25:43Z and marked failed at 2026-09-30T07:26:46Z, exactly 30 days later. That is the pattern of a pull_request workflow from a first-time contributor that nobody approved and that GitHub expired. No lint check ever ran, and the commit's two one-line Python changes cannot affect workflow scheduling.

    Full reasoning on HUD →

UNCLASSIFIED FAILURES - DrCI could not classify the following jobs because the workflow did not run on the merge base. The failures may be pre-existing on trunk or introduced by this PR:

  • Auto Request Review (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)

    AI verdict: AI verdict: infra issue

    The 'Auto Request Review' run for this PR (run 33368329968) came from a fork (tgrhn/pytorch) and finished as 'failure' without creating any jobs or logs, so it never actually ran. The suspect commit only adds self.is_mps to a condition in two decomposition files, and nothing in the workflow touches those files.

    Full reasoning on HUD →

  • docs-build (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)

    AI verdict: AI verdict: infra issue

    The docs-build run on the suspect (run 33368330204) finished as "failure" without creating a single job. Lint, BC Lint, pull and Auto Request Review all failed the same way at the same moment. Other contributors' PRs that hour show the same zero-job failures. The suspect only changes two lines in Python decomposition files, which can't stop a workflow from starting.

    Full reasoning on HUD →

  • pull (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)

    AI verdict: AI verdict: infra issue

    The 'pull' workflow run for this SHA has zero jobs. It was created 2026-08-31 and marked failed exactly 30 days later, which looks like a run that expired while waiting for approval, not a real CI outcome. The suspect only changes two Python lines in torch/_decomp, which can't stop a workflow from starting. The inductor workflow on the same SHA passed all of its executed checks.

    Full reasoning on HUD →

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot

pytorch-bot Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@egeboy35

egeboy35 commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Not a maintainer, and I have no Apple hardware so I could not execute the MPS path - but I read the three allocations and your premise holds exactly. MPS is byte-for-byte CUDA here, not CPU:

// mps/operations/ActivationKernel.mm:318
auto buffer = at::empty({0}, self.options());
// cuda/Activation.cpp:91
auto buffer = at::empty({0}, input.options());
// native/Activation.cpp:769   <- the odd one out
auto buffer = at::empty_like(input, at::MemoryFormat::Contiguous);

and log_sigmoid_forward_out_mps says so in as many words: // NOTE: buffer is only used by CPU dispatch, we just ignore it here.

Two things I checked that might be useful to state in the PR:

This completes the condition rather than extending it. log_sigmoid_forward dispatches to exactly four backends - CPU, CUDA, MPS, XPU (native_functions.yaml:12240-12248). After your change the else branch holds CPU alone, which is the only one of the four that allocates a full-shape buffer. So the enumeration is now exhaustive for in-tree backends, not just one entry longer.

The allowlist still cannot be inverted, which I think supports the #194355 framing. With three of four devices enumerated, if not self.is_cpu looks like the obvious simplification, but it would silently change meta tensors:

meta tensor today                  -> buffer (2, 3)
with `not self.is_cpu`             -> buffer (0,)
aten's own meta kernel returns     -> buffer (2, 3)

A meta tensor has is_cpu == False and today lands in the CPU branch, which happens to agree with what torch.ops.aten.log_sigmoid_forward returns on a meta input. So the device test cannot be expressed as a negation, and the only way out is the dispatch-based approach the RFC proposes. Might be worth a sentence in the PR body, since "why not just invert it" is the first question a reviewer will have.

Nothing blocking from me - the change reads correct and both copies of the duplicated decomposition are covered.

_🤖 Investigated and drafted with Claude Code; the source reads and the meta-tensor numbers above are mine, run and reviewed before posting.

@youlituao

Copy link
Copy Markdown
Contributor

Thanks for catching and fixing this — the MPS kernel source reading confirms
the premise, and the analysis of the meta-tensor divergence (and why CUDA
handled it via expected failures rather than changing the decomposition) is
exactly right.

One suggestion, offered as non-blocking: rather than extending the
enumeration with is_mps, consider flipping the branch to the closed side of
the contract. We just reproduced the identical failure on an out-of-tree
PrivateUse1 device (Ascend NPU): its native log_sigmoid_forward allocates
an empty (0,) buffer like CUDA/XPU/MPS, and CrossRefFakeMode raises the
same MetadataMismatchError (output[1]: torch.Size([0]) vs
torch.Size([4])). With the enumeration approach, that device is the next
round of the same ride (#141333 → this PR → next backend).

The set of devices whose kernels materialize the buffer is exactly {cpu},
plus {meta}: meta tensors have no device, and this op has no Meta kernel
(native_functions.yaml registers only CPU/CUDA/MPS/XPU), so the decomposition
is what aten.log_sigmoid_forward returns on meta inputs — meta must keep
taking the CPU branch. (This is also why a plain not self.is_cpu doesn't
work: it would silently flip meta to the empty branch and break the
decomp-vs-meta agreement.) Enumerating that closed side instead:

if self.is_cpu or self.is_meta:
    buffer = z
else:
    buffer = self.new_zeros((0,))

Two implementation notes if you go this route:

  1. Tensor.is_privateuseone exists in C++ (TensorBase::is_privateuseone)
    but is not exposed as a Python Tensor property, so the accelerator side
    cannot be expressed as a positive predicate — that's what makes the
    closed-side enumeration the only in-decomposition form that generalizes.
  2. The twin copy in decompositions_for_jvp.py is torch.jit.script-ed at
    import (use_python=False); worth verifying is_cpu/is_meta script
    cleanly there (the trace registration in the same file has a
    use_python=True precedent as a fallback).

Optionally, a small regression test pinning the contract would protect the
next backend — test/test_decomp.py (owner: module: decompositions) is a
collision-free home; test/test_fake_tensor.py is being reworked in #193986,
so adding there would create avoidable churn. Happy to share a ready-made
diff for both files plus the test, and the out-of-tree verification steps,
if useful.

Nothing blocking from my side — maintainer's call whether the enumeration or
the closed-side form is preferred here.

youlituao added a commit to youlituao/pytorch that referenced this pull request Sep 22, 2026
The log_sigmoid_forward decomposition decided the shape of its second
output (buffer) by enumerating CUDA and XPU. Backends whose kernels
materialize the buffer are exactly {cpu} plus {meta} (meta has no device
and the op has no Meta kernel, so the decomposition defines its meta
behavior) — enumerate that closed side instead, so CUDA/XPU/MPS and every
PrivateUse1 backend get the empty `(0,)` buffer consistently in both the
real kernels and FakeTensor inference.

Fixes the MetadataMismatchError class seen on XPU (pytorch#141333), MPS (pytorch#195417)
and out-of-tree PrivateUse1 devices.

Also adds the missing `hw_classification` class attributes to
test/test_decomp.py (per the pytorch#190991 convention) so the new regression
test is picked up by device-parameterized CI runs.

Part of the device-decoupling sweep (pytorch#194355).
youlituao added a commit to youlituao/pytorch that referenced this pull request Oct 10, 2026
The log_sigmoid_forward decomposition decided the shape of its second
output (buffer) by enumerating CUDA and XPU. Backends whose kernels
materialize the buffer are exactly {cpu} plus {meta} (meta has no device
and the op has no Meta kernel, so the decomposition defines its meta
behavior) — enumerate that closed side instead, so CUDA/XPU/MPS and every
PrivateUse1 backend get the empty `(0,)` buffer consistently in both the
real kernels and FakeTensor inference.

Fixes the MetadataMismatchError class seen on XPU (pytorch#141333), MPS (pytorch#195417)
and out-of-tree PrivateUse1 devices.

Also adds the missing `hw_classification` class attributes to
test/test_decomp.py (per the pytorch#190991 convention) so the new regression
test is picked up by device-parameterized CI runs.

Part of the device-decoupling sweep (pytorch#194355).
youlituao added a commit to youlituao/pytorch that referenced this pull request Oct 10, 2026
The log_sigmoid_forward decomposition decided the shape of its second
output (buffer) by enumerating CUDA and XPU. The buffer is materialized
only by log_sigmoid_backward_cpu; the CUDA/XPU/MPS kernels allocate an
empty (0,) buffer and ignore it (see the NOTE comments in
log_sigmoid_backward_{cuda,mps}), and we verified the same on a
PrivateUse1 device. Enumerate the evidence-backed empty-buffer devices
(cuda/xpu/mps + the PrivateUse1 backend via its registered name) while
keeping cpu and meta on the full-shape branch — meta has no device and
the op has no Meta kernel, so the decomposition defines its meta
behavior. Backends not listed keep their historical full-shape buffer:
no behavioral delta beyond the two fixes (MPS per pytorch#195417, PrivateUse1
per our device verification).

Fixes the MetadataMismatchError class seen on XPU (pytorch#141333), MPS
(pytorch#195417) and out-of-tree PrivateUse1 devices.

Also adds the missing `hw_classification` class attributes to
test/test_decomp.py (per the pytorch#190991 convention) so the new regression
test is picked up by device-parameterized CI runs.

Part of the device-decoupling sweep (pytorch#194355).
pytorchmergebot pushed a commit to youlituao/pytorch that referenced this pull request Oct 13, 2026
The log_sigmoid_forward decomposition decided the shape of its second
output (buffer) by enumerating CUDA and XPU. The buffer is materialized
only by log_sigmoid_backward_cpu; the CUDA/XPU/MPS kernels allocate an
empty (0,) buffer and ignore it (see the NOTE comments in
log_sigmoid_backward_{cuda,mps}), and we verified the same on a
PrivateUse1 device. Enumerate the evidence-backed empty-buffer devices
(cuda/xpu/mps + the PrivateUse1 backend via its registered name) while
keeping cpu and meta on the full-shape branch — meta has no device and
the op has no Meta kernel, so the decomposition defines its meta
behavior. Backends not listed keep their historical full-shape buffer:
no behavioral delta beyond the two fixes (MPS per pytorch#195417, PrivateUse1
per our device verification).

Fixes the MetadataMismatchError class seen on XPU (pytorch#141333), MPS
(pytorch#195417) and out-of-tree PrivateUse1 devices.

Also adds the missing `hw_classification` class attributes to
test/test_decomp.py (per the pytorch#190991 convention) so the new regression
test is picked up by device-parameterized CI runs.

Part of the device-decoupling sweep (pytorch#194355).
pytorchmergebot pushed a commit that referenced this pull request Oct 15, 2026
… device-agnostic instead of backend-enumerated (#197530)

## Summary

`log_sigmoid_forward` returns `(output, buffer)`. The buffer is only consumed
by the CPU backward kernel (`log_sigmoid_backward_cpu`); the CUDA/XPU/MPS
forward kernels (`log_sigmoid_forward_{cuda,mps}`) allocate an empty `(0,)`
buffer and ignore its contents (the "buffer is only used by CPU dispatch, we
just ignore it here" NOTE also appears in some backward and out variants, e.g.
`log_sigmoid_backward_cuda` and `log_sigmoid_forward_out_mps`). PrivateUse1
(out-of-tree) backends follow the accelerator semantics: we verified on
torch_npu (Ascend) that the real kernel returns an empty `(0,)` buffer.

The decomposition in `torch/_decomp/decompositions.py` (used for FakeTensor
shape inference under `torch.compile`/export and `CrossRefFakeMode`) decided
the buffer shape by enumerating backends:

    if self.is_cuda or self.is_xpu:
        buffer = self.new_zeros((0,))
    else:
        buffer = z

Every time a new backend was added, someone had to extend this enumeration and
until then FakeTensor inference disagreed with the real kernel, making
`torch.compile`/export/`CrossRefFakeMode` fail with a `MetadataMismatchError`
on that backend: XPU in #141332/#141333, MPS in #195417, and we reproduced the
identical failure on an out-of-tree PrivateUse1 device:

    MetadataMismatchError: When comparing the output of
    aten.log_sigmoid_forward.default on FakeTensor and concrete Tensors, found
    mismatched tensor metadata for output[1]: Shapes torch.Size([0]) and
    torch.Size([4]) are not equal!

This PR makes the empty-buffer set explicit and evidence-backed — cuda/xpu/mps
(source-verified) plus PrivateUse1 (verified on device, where the real kernel
returns `(0,)` and the old enumeration produced a full-shape buffer that broke
`CrossRefFakeMode`) — while **every backend not in that list (XLA, HPU, MTIA,
and any backend whose contract is unverified) keeps the historical full-shape
buffer**: no behavioral delta beyond the two fixes.

## Changes

- `torch/_decomp/decompositions.py` and `torch/_decomp/decompositions_for_jvp.py`
  (the twin copies must stay in lockstep — upstream precedent #141333/#195417):
  the branch now enumerates the evidence-backed empty-buffer devices and keeps
  the historical full-shape default for everything else:

      if self.is_cpu or self.is_meta:
          buffer = z
      elif (
          self.is_cuda
          or self.is_xpu
          or self.is_mps
          or self.device.type == torch._C._get_privateuse1_backend_name()
      ):
          buffer = self.new_zeros((0,))
      else:
          buffer = z

  Design notes: (a) meta tensors stay on the full branch — this op has no Meta
  kernel, so the decomposition defines its meta behavior, and `not
  self.is_cpu` alone would silently flip meta to the empty branch; (b)
  `Tensor.is_privateuseone` is not exposed as a Python property, so the
  PrivateUse1 backend is identified via its registered name
  (`torch._C._get_privateuse1_backend_name()`, called at runtime — no
  import-time freeze); (c) backends whose contract is unverified keep the
  historical default — no behavioral delta beyond the two fixes.
- Added a regression test `TestDecomp::test_log_sigmoid_forward_buffer_shape`
  (in `test/test_decomp.py`, owner: `module: decompositions`) calling the
  production symbols through `FakeTensorMode`: buffer full-shape for cpu,
  empty for cuda, **empty for mps (the discriminating leg — the pre-PR
  enumeration gives a full-shape buffer for mps, so the test fails without
  this fix)**, empty for PrivateUse1 (the backend name is resolved at runtime
  via `torch._C._get_privateuse1_backend_name()` and pinned with an explicit
  `:0` index, so renamed trees are covered and fake creation skips the
  `is_initialized` lookup in `FakeTensor._normalize_fake_device`), full for
  meta. `@onlyCPU` per the file's convention for device-agnostic tests (the
  assertions pivot on fake/meta devices).
- Added the `hw_classification` class attributes `test/test_decomp.py` was
  missing (TestDecomp / DecompOneOffTests → ACCELERATOR, HasDecompTest →
  GENERIC, per the #190991 convention) so the new test is picked up by
  device-parameterized CI runs.
- Removed the two `fake_backward_mps_xfails` entries in `test/test_ops.py`
  for `nn.functional.logsigmoid` and
  `nn.functional.binary_cross_entropy_with_logits` (the latter decomposes
  through `logsigmoid`). They were added on main to mask exactly the
  fake-vs-real MPS buffer mismatch this PR fixes; with the fix in place
  they report unexpected successes. The remaining entries mask unrelated
  mismatches and stay.

| device | before | after | delta |
|---|---|---|---|
| CPU | full buffer | full buffer | none |
| CUDA / XPU | empty `(0,)` | empty `(0,)` | none |
| MPS | full buffer (wrong, mismatched the real kernel) | empty `(0,)` | **fixes the #195417 mismatch** |
| meta (incl. device-less) | full buffer | full buffer | none |
| PrivateUse1 (FakeTensor) | full buffer (wrong, mismatched the real kernel) | empty `(0,)` | **fixes the mismatch** |
| XLA / HPU / MTIA / unknown | full buffer (historical) | full buffer (unchanged) | none — preserved |

## Depends on

- **#190991** (`HardwareClassification` enum) — used by the added labels.
  Already merged; present in trunk.
- No other merge dependencies. Relations, not dependencies: #195417 (same
  condition, enumeration fix — the evidence-backed form here subsumes it) and
  #193116 (XPU enablement of the same suite, orthogonal).

## Not changed

- The `test_meta.py` crossref expected failures for `log_sigmoid_forward` on
  cuda/xpu (#196554-style) are intentionally untouched: those are about
  device-less meta tensors vs real kernels, and meta behavior is unchanged.
- Pre-existing method-level `@onlyCPU` / `@onlyCUDA` gates in
  `test/test_decomp.py` are left untouched — most encode per-method device
  semantics (RNG determinism, precision, CUDA-specific NaN behavior,
  CPU-only reference behavior), a few are legacy CPU scoping that
  device-enablement efforts like #193116 are better positioned to remove.
- `torch_npu` requires no changes: its native `log_sigmoid_forward` already
  returns an empty `(0,)` buffer (verified on device), so the fix aligns
  FakeTensor inference with the real kernel.

## Test plan

- [x] NPU (PrivateUse1, torch_npu 2.13.0+git45fbeae, Ascend 910B3):
      `CrossRefFakeMode` + `F.logsigmoid` raised `MetadataMismatchError`
      before this PR (output[1] `(0,)` vs `(4,)`) and passes after;
      probe `aten.log_sigmoid_forward` buffer stays `(0,)`;
      new UT green on the box (cpu variant; `@onlyCPU` skips the real npu
      variant by design — the in-test fake PrivateUse1 leg resolves to
      `npu:0` on this tree and passes; real-kernel behavior is additionally
      covered by the probes).
- [x] CPU: new UT 1 passed; `test/functorch/test_ops.py -k logsigmoid`
      14 OK; `test_meta.py -k logsigmoid` 12 passed / 14 skipped (xfails
      unchanged).
- [x] CUDA (A100, torch 2.13.0a0): probe `(0,)` unchanged; functorch 28 OK;
      test_meta 52 tests OK (skipped=27); new UT 2 passed (cpu + cuda
      variants, pre-`@onlyCPU` form).
- [ ] CI (lint / unittest shards).

Pull Request resolved: #197530
Approved by: https://github.com/jansel, https://github.com/guangyey
@tgrhn
tgrhn marked this pull request as ready for review October 19, 2026 02:26
@github-actions github-actions Bot added bot-triaged This is a label only to be used by the auto triage bot missing actionable issue A PR without a linked actionable issue or maintainer sponsor triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module labels Oct 19, 2026
@tgrhn

tgrhn commented Oct 21, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @egeboy35 and @youlituao for the careful reads.

@youlituao, I looked into is_cpu or is_meta, but CPU and meta aren't the only backends that materialize the buffer. torch_xla registers its own log_sigmoid_forward, and its lowering (BuildLogSigmoid in torch_xla/csrc/elementwise.cpp) returns a full input-shaped buffer. Its log_sigmoid_backward reads that buffer too: grad_output * (-max_deriv - sign * (buffer - 1) / buffer). Today XLA takes the else branch and fake/real shapes agree. With is_cpu or is_meta, the decomposition would give XLA a (0,) buffer: the same mismatch in the other direction, plus a backward that would read an empty buffer.

Out-of-tree backends go both ways here (NPU allocates (0,), XLA the full shape), so any device list in the decomposition will be wrong for some backend. The decomposition can't ask the backend what it allocates, and that is the problem #194355 is about. I'd like to keep this PR to the in-tree MPS fix and handle PrivateUse1 under the RFC.

@egeboy35, good point. I've added the "why not invert it" note to the description.

@guangyey @malfet could one of you review this? It's the MPS counterpart of #141333: the same one-line change in both copies of the decomposition.

@tgrhn

tgrhn commented Oct 21, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "release notes: mps" "topic: bug fixes"

This branch was previously deployed

1 inactive deployment
bedrock — 3cbbf8de Deployed Oct 19, 2026 by tgrhn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-triaged This is a label only to be used by the auto triage bot ciflow/inductor missing actionable issue A PR without a linked actionable issue or maintainer sponsor open source release notes: accelerator release notes: mps Release notes category topic: bug fixes topic category topic: improvements topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants