[MPS] `nll_loss`/`cross_entropy` 会在目标元素位于平面索引 2**31 或更大的行中默默返回 0
import torch import torch.nn.functional as F torch.manual_seed(0) N, C = 223 + 216, 256 # input has 231 + 224 elements x = torch.rand(N, C) * 8 - 4 t = torch.randint(0, C, (N,)) xm, tm = x.to("mps"), t.to("mps")
loss = F.cross_entropy(xm, tm, reduction="none").cpu() ref = F.cross_entropy(x, t, reduction="none") # CPU bad = (loss - ref).abs() > 1e-4 beyond = torch.arange(N) * C + t >= 231 # flat index of the target element print("wrong rows:", bad.sum().item(), "| rows whose target lies at flat index >= 231:", beyond.sum().item(), "| same rows:", torch.equal(bad, beyond), "| wrong values that are 0:", (loss[bad] == 0).sum().item()) print("sum on MPS:", F.cross_entropy(xm, tm, reduction="sum").item(), "| CPU:", ref.double().sum().item()) print("-log_softmax(x).gather(...).sum() on MPS:", (-F.log_softmax(xm, -1).gather(1, tm[:, None])).sum().item()) Output on PyTorch 2.14.0, macOS 27.0 (26A428), MacBook Pro M2 Max 96 GB:
内容来源: pytorch/pytorch