Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

An attempt to add MPS device to torch backend #750

Merged
merged 2 commits into from
Aug 19, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions keras_core/backend/torch/core.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import contextlib
import os

import numpy as np
import torch
Expand All @@ -12,7 +13,18 @@
from keras_core.utils.nest import pack_sequence_as

DYNAMIC_SHAPES_OK = True
DEFAULT_DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
# Some operators such as 'aten::_foreach_mul_.Scalar'
# are not currently implemented for the MPS device.
# check https://github.com/pytorch/pytorch/issues/77764.
if (
torch.backends.mps.is_available()
and os.getenv("PYTORCH_ENABLE_MPS_FALLBACK") == "1"
):
DEFAULT_DEVICE = "mps"
elif torch.cuda.is_available():
DEFAULT_DEVICE = "cuda"
else:
DEFAULT_DEVICE = "cpu"

TORCH_DTYPES = {
"float16": torch.float16,
Expand Down Expand Up @@ -145,7 +157,7 @@ def transform(x):
if x.requires_grad:
x = x.detach()
# Tensor has to be moved to CPU before converting to numpy.
if x.is_cuda:
if x.is_cuda or x.is_mps:
x = x.cpu()
return np.array(x)

Expand Down