-
Notifications
You must be signed in to change notification settings - Fork 34
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a workaround for invalid outputs of
nn.Linear
on MPS (#124)
`nn.Linear` produces incorrect outputs with certain matrix sizes when using the MPS backend: pytorch/pytorch#97239 The actual issue is in the underlying `torch.nn.functional.linear` function. Work around this by using an explicit matrix multiplication when the MPS backend is used.
- Loading branch information
Showing
4 changed files
with
22 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
import torch | ||
from torch import Tensor | ||
import torch.nn as nn | ||
import torch.nn.functional as F | ||
|
||
|
||
class Linear(nn.Linear): | ||
def forward(self, input: Tensor) -> Tensor: | ||
# Work around issue with linear with the MPS backend. See: | ||
# https://github.com/pytorch/pytorch/issues/97239 | ||
if hasattr(input, "is_mps") and input.is_mps: | ||
return torch.matmul(input, self.weight.t()) + self.bias | ||
else: | ||
return F.linear(input, self.weight, self.bias) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters