Zero-copy CUDA tensor from a raw device pointer.
(
ptr: int,
shape: tuple[int, ...],
dtype: torch.dtype,
device: torch.device,
numel: int,
total_bytes: int,
)
| 156 | # CUDA implementation # |
| 157 | # ====================================================================== # |
| 158 | def _tensor_from_cuda_ptr( |
| 159 | ptr: int, |
| 160 | shape: tuple[int, ...], |
| 161 | dtype: torch.dtype, |
| 162 | device: torch.device, |
| 163 | numel: int, |
| 164 | total_bytes: int, |
| 165 | ) -> torch.Tensor: |
| 166 | """Zero-copy CUDA tensor from a raw device pointer.""" |
| 167 | |
| 168 | try: |
| 169 | _DTYPE_TO_TYPESTR = { |
| 170 | torch.float16: "<f2", |
| 171 | torch.float32: "<f4", |
| 172 | torch.float64: "<f8", |
| 173 | torch.int8: "|i1", |
| 174 | torch.int16: "<i2", |
| 175 | torch.int32: "<i4", |
| 176 | torch.int64: "<i8", |
| 177 | torch.uint8: "|u1", |
| 178 | torch.bool: "|b1", |
| 179 | } |
| 180 | is_bf16 = dtype == torch.bfloat16 |
| 181 | |
| 182 | # Determine the correct typestr, smuggle bfloat16 as int16 |
| 183 | typestr = "<i2" if is_bf16 else _DTYPE_TO_TYPESTR.get(dtype, "|u1") |
| 184 | |
| 185 | class _CudaArrayWrapper: |
| 186 | def __init__(self, ptr_int: int, shape_tuple: tuple, type_str: str): |
| 187 | self.__cuda_array_interface__ = { |
| 188 | "data": (ptr_int, False), |
| 189 | "shape": shape_tuple, |
| 190 | "typestr": type_str, |
| 191 | "version": 3, |
| 192 | } |
| 193 | |
| 194 | t = torch.as_tensor(_CudaArrayWrapper(ptr, (numel,), typestr), device=device) |
| 195 | if is_bf16: |
| 196 | t = t.view(torch.bfloat16) |
| 197 | |
| 198 | return t.view(*shape) |
| 199 | except Exception: |
| 200 | pass |
| 201 | |
| 202 | # Strategy 2: cudaMemcpy Device-to-Device (Fallback) |
| 203 | libcudart = _get_copy_lib() |
| 204 | if libcudart is None: |
| 205 | raise RuntimeError("Failed to load libcudart/libamdhip") |
| 206 | |
| 207 | cudaMemcpy = libcudart.cudaMemcpy |
| 208 | cudaMemcpy.restype = ctypes.c_int |
| 209 | cudaMemcpy.argtypes = [ |
| 210 | ctypes.c_void_p, |
| 211 | ctypes.c_void_p, |
| 212 | ctypes.c_size_t, |
| 213 | ctypes.c_int, |
| 214 | ] |
| 215 | _MEMCPY_D2D = 3 |
no test coverage detected