Repository navigation
Conversation
`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.
🔗 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 FailuresAs of commit 3cbbf8d with merge base 33812ec ( NEW FAILURES - The following jobs have failed:
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:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
|
|
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 Two things I checked that might be useful to state in the PR: This completes the condition rather than extending it. The allowlist still cannot be inverted, which I think supports the #194355 framing. With three of four devices enumerated, A meta tensor has 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. |
|
Thanks for catching and fixing this — the MPS kernel source reading confirms One suggestion, offered as non-blocking: rather than extending the The set of devices whose kernels materialize the buffer is exactly if self.is_cpu or self.is_meta:
buffer = z
else:
buffer = self.new_zeros((0,))
Two implementation notes if you go this route:
Optionally, a small regression test pinning the contract would protect the Nothing blocking from my side — maintainer's call whether the enumeration or |
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).
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).
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).
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).
… 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
|
Thanks @egeboy35 and @youlituao for the careful reads. @youlituao, I looked into Out-of-tree backends go both ways here (NPU allocates @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. |
|
@pytorchbot label "release notes: mps" "topic: bug fixes" |
Summary
log_sigmoid_forward's decomposition (used for FakeTensor/meta shapeinference, e.g. under
CrossRefFakeModeandtorch.compile) onlyspecial-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_backwardkernels have always allocated
bufferasat::empty({0}, ...)and ignoredits 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.pyandtorch/_decomp/decompositions_for_jvp.py); MPS was never added alongsideXPU at the time. This PR adds
self.is_mpsto the same condition in bothfiles.
Why not
not self.is_cpu? Meta tensors haveis_cpu == False, and this op has no Meta kernel, so the decomposition is whataten.log_sigmoid_forwardreturns on meta inputs. Meta has to keep the full buffer, and inverting the check would change it to(0,).is_cpu or is_metadoesn'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:
MetadataMismatchError: ... found mismatched tensor metadata for output[1]: Shapes torch.Size([0]) and torch.Size([5]) are not equal!forward/backward and forward-mode-AD double backward (which is what
decompositions_for_jvp.py's version is used for) -- max diffs atfp32 precision level (
1.19e-07/3.73e-09)lintrunner -aon both changed files: clean