StridedMemoryView.__dlpack__ raises BufferError for bfloat16 views
Is this a duplicate?
- [x] I confirmed there appear to be no duplicate issues for this bug and that I agree to the Code of Conduct
Type of Bug
Runtime Error
Component
cuda.core
Describe the bug
A StridedMemoryView with an ml_dtypes.bfloat16 dtype cannot be exported over DLPack. _smv_dtype_numpy_to_dlpack (cuda/core/_memoryview.pyx) picks the type code from numpy.dtype.kind, and numpy.dtype(ml_dtypes.bfloat16).kind is "V", so bf16 falls through to the error. DLPack import already accepts kDLBfloat, the dtype property documents bfloat16, and _tensor_map.pyx already maps ml_dtypes.bfloat16 to kDLBfloat. So a bf16 tensor from PyTorch, CuPy or JAX can be viewed but not re-exported.
test_dlpack_export_roundtrip_dtypes[bfloat16] does not catch this because its NumPy consumer skips bf16.
How to Reproduce
cuda-core 1.2.2, ml_dtypes, numpy (host memory is enough):
import numpy as np, ml_dtypes
from cuda.core.utils import StridedMemoryView
bf16 = np.dtype(ml_dtypes.bfloat16)
src = np.zeros((2, 3), dtype=np.uint16)
view = StridedMemoryView.from_any_interface(src, stream_ptr=-1).view(dtype=bf16)
view.__dlpack__()
BufferError: Unsupported dtype for DLPack export: bfloat16
float16 and uint16 views of the same array export fine.
Expected behavior
The view exports with type code kDLBfloat and 16 bits, and StridedMemoryView.from_dlpack on the result gives a bfloat16 view of the same memory.
Operating System
Ubuntu 24.04, aarch64
nvidia-smi output
Not GPU-specific; host memory is enough.
Proposed fix
I have a fix ready: map ml_dtypes.bfloat16 to kDLBfloat before the kind dispatch, plus a host-memory round-trip test. With a source build of main and of the fix, the snippet above raises on main, and with the fix the export succeeds and re-imports as bfloat16 with the same pointer; an unsupported V4 dtype is still rejected. Happy to open a PR if you assign this to me.
Taking this one. Plan: teach _smv_dtype_numpy_to_dlpack in cuda/core/_memoryview.pyx to map ml_dtypes.bfloat16 to kDLBfloat (16 bits) ahead of the kind-based dispatch, mirroring the import side's existing kDLBfloat handling, and add a StridedMemoryView.from_dlpack round-trip test that does not depend on NumPy's own extended-dtype DLPack support. PR shortly.
(Prepared with an AI coding agent; I review, test, and stand behind the change.)
@Sainath-Reddy7 please read our contributor guide and wait for a team member to assign first. Please do not send unsolicited PRs.
Hi @leofang , thanks for the correction. You're right, I should have waited for a team member to assign the issue before opening the PR. I've read the contributor guide now and will follow the assignment-first process going forward. Also happy to work with @seberg on the review feedback on the PR.