Fix np bfloat16 misinterpreted as complex#3146
Open
kellen-sun wants to merge 11 commits intoml-explore:mainfrom
Open
Fix np bfloat16 misinterpreted as complex#3146kellen-sun wants to merge 11 commits intoml-explore:mainfrom
kellen-sun wants to merge 11 commits intoml-explore:mainfrom
Conversation
awni
reviewed
Feb 19, 2026
python/src/array.cpp
Outdated
Comment on lines
300
to
326
| if (nb::hasattr(v, "dtype")) { | ||
| if (nb::str(v.attr("dtype")).equal(nb::str("bfloat16"))) { | ||
| auto type_mod = nb::str(v.attr("__class__").attr("__module__")); | ||
| if (type_mod.equal(nb::str("numpy")) || | ||
| type_mod.equal(nb::str("ml_dtypes"))) { | ||
| auto np = nb::module_::import_("numpy"); | ||
| auto contig_obj = np.attr("ascontiguousarray")(v); | ||
| mx::Shape shape; | ||
| nb::tuple shape_tuple = nb::cast<nb::tuple>(v.attr("shape")); | ||
| size_t ndim = shape_tuple.size(); | ||
| for (size_t i = 0; i < ndim; ++i) { | ||
| shape.push_back(nb::cast<int>(shape_tuple[i])); | ||
| } | ||
| uint64_t ptr_int = nb::cast<uint64_t>( | ||
| contig_obj.attr("ctypes").attr("data")); | ||
| const mx::bfloat16_t* typed_ptr = | ||
| reinterpret_cast<const mx::bfloat16_t*>(ptr_int); | ||
| auto res = (ndim == 0) | ||
| ? mx::array(*typed_ptr, mx::bfloat16) | ||
| : mx::array(typed_ptr, shape, mx::bfloat16); | ||
| if (t.has_value()) | ||
| res = mx::astype(res, *t); | ||
| new (aptr) mx::array(res); | ||
| return; | ||
| } | ||
| } | ||
| } |
Member
There was a problem hiding this comment.
This should really be done in the create_array function. That way other conversions from numpy bfloat16 will work.
Contributor
Author
There was a problem hiding this comment.
we can probably move the code to create_array, but the fix does require capturing a general nb::object from init because of how the bfloat16 falls into complex, so we'll need to change the signature on create_array as well and how it's called. If so, I've added a fix, with an additional test case (the other valid use for create_array with bfloat16).
Here's the output of that case if run from main:
> a_asarray = mx.asarray(x_vector)
^^^^^^^^^^^^^^^^^^^^
E ValueError: Invalid type ndarray received in array initialization.
python/tests/test_bf16.py:221: ValueError
This file contains hidden or 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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Proposed changes
Fixes #1075
Bug: The bug happens when converting
np.array(1., dtype=ml_dtypes.bfloat16)andnp.array([1.], dtype=ml_dtypes.bfloat16)tomx.array(x). For the former case, it'll silently be caught as astd::complexas part ofArrayInitTypeand get converted as such (see related issue for code). For the latter, it'll be interpreted as anArrayLike, not be able to make the conversion tomx.array()and raise aValueError.The Fix: We need to catch this case before it gets filtered by
ArrayInitType. I made thearray.__init__more generic to catch this and checked the dtype to match bfloat16, then manually construct the array. Otherwise, we fallback to the originalArrayInitTypecase.Note: bfloat16, is the only current ml_dtype that mlx supports.
Verification: Verified locally (macOS 26.2, MLX 0.30.7, Apple M2) with the additional test case I provided. If this is run from main, it raises the bug mentioned above:
Checklist
Put an
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changes