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

[MLX] [bugfix] Preserve dtype of array when converting to torch #1349

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
6 changes: 3 additions & 3 deletions outlines/processors/base_logits_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,9 @@ def _to_torch(tensor_like: Array) -> torch.Tensor:
import mlx.core as mx

# https://ml-explore.github.io/mlx/build/html/usage/numpy.html#pytorch
return torch.from_dlpack(
np.array(tensor_like.astype(mx.float32), copy=False)
)
if tensor_like.dtype == mx.bfloat16:
tensor_like = tensor_like.astype(mx.float32)
return torch.from_dlpack(np.array(tensor_like, copy=False))

elif is_jax_array_type(type(tensor_like)):
import jax
Expand Down
8 changes: 7 additions & 1 deletion tests/processors/test_base_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import mlx.core as mx

arrays["mlx"] = mx.array([[1, 2], [3, 4]], dtype=mx.float32)
arrays["mlx_bfloat16"] = mx.array([[1, 2], [3, 4]], dtype=mx.bfloat16)
except ImportError:
pass

Expand Down Expand Up @@ -59,7 +60,12 @@ def test_from_torch(array_type, processor):
torch_tensor = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)
data = processor._from_torch(torch_tensor, type(arrays[array_type]))
assert isinstance(data, type(arrays[array_type]))
assert np.allclose(data, arrays[array_type])
if array_type == "mlx_bfloat16":
# For bfloat16, we expect the output to be float32 due to the conversion
assert data.dtype == mx.float32
assert np.allclose(np.array(data), np.array([[1, 2], [3, 4]], dtype=np.float32))
else:
assert np.allclose(data, arrays[array_type])


@pytest.mark.parametrize("array_type", arrays.keys())
Expand Down
Loading