|
| 1 | +import ctypes as ct |
| 2 | +from math import prod |
| 3 | +from typing import Optional |
| 4 | + |
| 5 | +import torch |
| 6 | + |
| 7 | +from .cextension import lib |
| 8 | +from .functional import CUBLAS_Context, _cuda_device_of, _get_tensor_stream, get_ptr, is_on_gpu |
| 9 | + |
| 10 | +_IS_TORCH_GTE_24 = False |
| 11 | + |
| 12 | +if hasattr(torch.library, "register_fake"): |
| 13 | + _IS_TORCH_GTE_24 = True |
| 14 | + register_fake = torch.library.register_fake |
| 15 | + register_kernel = torch.library.register_kernel |
| 16 | +else: |
| 17 | + # PyTorch <= 2.3 |
| 18 | + register_fake = torch.library.impl_abstract |
| 19 | + register_kernel = torch.library.impl |
| 20 | + |
| 21 | +# Define op |
| 22 | +# TODO: mutable output arg as alias of return can be challenging; |
| 23 | +# consider a separate op without aliased return: |
| 24 | +# int8_linear_matmul_out( |
| 25 | +# Tensor A, Tensor B, Tensor out, ScalarType dtype=int32 |
| 26 | +# ) -> None |
| 27 | +torch.library.define( |
| 28 | + "bitsandbytes::int8_linear_matmul", |
| 29 | + "(Tensor A, Tensor B, Tensor(a!)? out=None, ScalarType dtype=int32) -> Tensor(a!)", |
| 30 | +) |
| 31 | + |
| 32 | + |
| 33 | +# Fake/abstract op |
| 34 | +@register_fake("bitsandbytes::int8_linear_matmul") |
| 35 | +def _(A: torch.Tensor, B: torch.Tensor, out: Optional[torch.Tensor] = None, dtype=torch.int32): |
| 36 | + shapeC = (*A.shape[:-1], B.shape[0]) |
| 37 | + if out is None: |
| 38 | + return torch.empty(shapeC, device=A.device, dtype=dtype) |
| 39 | + return out |
| 40 | + |
| 41 | + |
| 42 | +# CPU implementation |
| 43 | +@register_kernel("bitsandbytes::int8_linear_matmul", "cpu") |
| 44 | +def _(A: torch.Tensor, B: torch.Tensor, out: Optional[torch.Tensor] = None, dtype=torch.int32): |
| 45 | + # Naive implementation: perform matmul in fp32 |
| 46 | + result = torch.matmul(A.float(), B.float().t()).to(torch.int32) |
| 47 | + if out is not None: |
| 48 | + result = out.copy_(result) |
| 49 | + return result |
| 50 | + |
| 51 | + |
| 52 | +# MPS impl |
| 53 | +@register_kernel("bitsandbytes::int8_linear_matmul", "mps") |
| 54 | +def _(A: torch.Tensor, B: torch.Tensor, out: Optional[torch.Tensor] = None, dtype=torch.int32): |
| 55 | + pass |
| 56 | + |
| 57 | + |
| 58 | +# XPU impl |
| 59 | +@register_kernel("bitsandbytes::int8_linear_matmul", "xpu") |
| 60 | +def _(A: torch.Tensor, B: torch.Tensor, out: Optional[torch.Tensor] = None, dtype=torch.int32): |
| 61 | + pass |
| 62 | + |
| 63 | + |
| 64 | +# Ascend NPU impl |
| 65 | +@register_kernel("bitsandbytes::int8_linear_matmul", "npu") |
| 66 | +def _(A: torch.Tensor, B: torch.Tensor, out: Optional[torch.Tensor] = None, dtype=torch.int32): |
| 67 | + pass |
| 68 | + |
| 69 | + |
| 70 | +# CUDA/ROCm impl |
| 71 | +@register_kernel("bitsandbytes::int8_linear_matmul", "cuda") |
| 72 | +def _(A: torch.Tensor, B: torch.Tensor, out: Optional[torch.Tensor] = None, dtype=torch.int32): |
| 73 | + A, B = B, A |
| 74 | + |
| 75 | + shapeA = A.shape |
| 76 | + shapeB = B.shape |
| 77 | + |
| 78 | + assert A.dtype == torch.int8 |
| 79 | + assert B.dtype == torch.int8 |
| 80 | + assert A.ndim == 2, "Only two dimensional matrices are supported for argument B" |
| 81 | + assert B.ndim in [2, 3], "Only two or three dimensional matrices are supported for argument A" |
| 82 | + assert prod(shapeB) > 0, f"Input tensor dimensions need to be > 0: {shapeB}" |
| 83 | + assert out is None or out.dtype == dtype |
| 84 | + |
| 85 | + shapeC = (*shapeB[:-1], shapeA[0]) |
| 86 | + |
| 87 | + k, m = shapeA |
| 88 | + n = prod(shapeB[:-1]) |
| 89 | + lda = shapeA[-1] # Weights (outputs, inputs) |
| 90 | + ldb = shapeB[-1] # Activations (batch, tokens, inputs) |
| 91 | + ldc = shapeC[-1] # Output (batch, tokens, outputs) |
| 92 | + |
| 93 | + assert ( |
| 94 | + lda == ldb |
| 95 | + ), f"int8_linear_matmul only supports B^T @ A. Inner dimensions do not match: B @ A = {shapeB} @ {shapeA}" |
| 96 | + |
| 97 | + # cuBLASLt does not support int8 matmul with inner dimensions that are not divisible by 4. |
| 98 | + # We'll fall back to a slower fp32 calculation in this circumstance. |
| 99 | + # Fortunately, this should not be very common. |
| 100 | + if lda % 4 != 0: |
| 101 | + result = torch.matmul(B.float(), A.float().t()).to(torch.int32) |
| 102 | + if out is not None: |
| 103 | + result = out.copy_(result) |
| 104 | + return result |
| 105 | + |
| 106 | + if out is None: |
| 107 | + out = torch.empty(shapeC, device=A.device, dtype=dtype) |
| 108 | + |
| 109 | + is_on_gpu([A, B, out]) |
| 110 | + |
| 111 | + with _cuda_device_of(A): |
| 112 | + ctx = CUBLAS_Context.get_instance().get_context(A.device) |
| 113 | + ptrA = get_ptr(A) |
| 114 | + ptrB = get_ptr(B) |
| 115 | + ptrC = get_ptr(out) |
| 116 | + ptrRowScale = None |
| 117 | + m = ct.c_int32(m) |
| 118 | + n = ct.c_int32(n) |
| 119 | + k = ct.c_int32(k) |
| 120 | + lda = ct.c_int32(lda) |
| 121 | + ldb = ct.c_int32(ldb) |
| 122 | + ldc = ct.c_int32(ldc) |
| 123 | + stream = _get_tensor_stream(A) |
| 124 | + |
| 125 | + if dtype == torch.int32: |
| 126 | + has_error = lib.cigemmlt_32(ctx, m, n, k, ptrA, ptrB, ptrC, ptrRowScale, lda, ldb, ldc, stream) |
| 127 | + else: |
| 128 | + has_error = lib.cigemmlt_8(ctx, m, n, k, ptrA, ptrB, ptrC, ptrRowScale, lda, ldb, ldc, stream) |
| 129 | + |
| 130 | + if has_error == 100: # `ERR_NOT_IMPLEMENTED` is defined as 100 in `ops.cu` |
| 131 | + raise NotImplementedError("int8_linear_matmul not implemented!") |
| 132 | + |
| 133 | + if has_error: |
| 134 | + raise RuntimeError( |
| 135 | + f"cublasLt ran into an error!\n" |
| 136 | + f"\t{shapeA=}, {shapeB=}, {shapeC=}\n" |
| 137 | + f"\t{(lda, ldb, ldc)=}\n" |
| 138 | + f"\t{(m, n, k)=}" |
| 139 | + ) |
| 140 | + |
| 141 | + return out |
0 commit comments