functional.py 79.9 KB
Newer Older
1
2
3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
Tim Dettmers's avatar
Tim Dettmers committed
4
# LICENSE file in the root directory of this source tree.
5
import ctypes as ct
Tom Aarsen's avatar
Tom Aarsen committed
6
import itertools
7
import operator
Tim Dettmers's avatar
Tim Dettmers committed
8
9
import random
import torch
Tim Dettmers's avatar
Tim Dettmers committed
10
import itertools
Tim Dettmers's avatar
Tim Dettmers committed
11
import math
Tim Dettmers's avatar
Tim Dettmers committed
12
from scipy.stats import norm
Tim Dettmers's avatar
Tim Dettmers committed
13
import numpy as np
14

Tom Aarsen's avatar
Tom Aarsen committed
15
from functools import reduce  # Required in Python 3
16
from typing import Tuple
Tim Dettmers's avatar
Tim Dettmers committed
17
18
from torch import Tensor

19
from .cextension import COMPILED_WITH_CUDA, lib
Tom Aarsen's avatar
Tom Aarsen committed
20

21
22
23
24

# math.prod not compatible with python < 3.8
def prod(iterable):
    return reduce(operator.mul, iterable, 1)
Max Ryabinin's avatar
Max Ryabinin committed
25

Tim Dettmers's avatar
Tim Dettmers committed
26
27
name2qmap = {}

Max Ryabinin's avatar
Max Ryabinin committed
28
if COMPILED_WITH_CUDA:
29
    """C FUNCTIONS FOR OPTIMIZERS"""
Max Ryabinin's avatar
Max Ryabinin committed
30
    str2optimizer32bit = {}
31
    str2optimizer32bit["adam"] = (lib.cadam32bit_grad_fp32, lib.cadam32bit_grad_fp16, lib.cadam32bit_grad_bf16)
32
    str2optimizer32bit["momentum"] = (
33
34
        lib.cmomentum32bit_grad_32,
        lib.cmomentum32bit_grad_16,
35
36
    )
    str2optimizer32bit["rmsprop"] = (
37
38
        lib.crmsprop32bit_grad_32,
        lib.crmsprop32bit_grad_16,
39
    )
Tim Dettmers's avatar
Tim Dettmers committed
40
    str2optimizer32bit["lion"] = (lib.clion32bit_grad_fp32, lib.clion32bit_grad_fp16, lib.clion32bit_grad_bf16)
41
    str2optimizer32bit["adagrad"] = (
42
43
        lib.cadagrad32bit_grad_32,
        lib.cadagrad32bit_grad_16,
44
    )
Max Ryabinin's avatar
Max Ryabinin committed
45
46

    str2optimizer8bit = {}
47
    str2optimizer8bit["adam"] = (
48
49
        lib.cadam_static_8bit_grad_32,
        lib.cadam_static_8bit_grad_16,
50
    )
51
    str2optimizer8bit["momentum"] = (
52
53
        lib.cmomentum_static_8bit_grad_32,
        lib.cmomentum_static_8bit_grad_16,
54
55
    )
    str2optimizer8bit["rmsprop"] = (
56
57
        lib.crmsprop_static_8bit_grad_32,
        lib.crmsprop_static_8bit_grad_16,
58
    )
59
    str2optimizer8bit["lion"] = (
60
61
        lib.clion_static_8bit_grad_32,
        lib.clion_static_8bit_grad_16,
62
    )
63
    str2optimizer8bit["lamb"] = (
64
65
        lib.cadam_static_8bit_grad_32,
        lib.cadam_static_8bit_grad_16,
66
    )
67
    str2optimizer8bit["lars"] = (
68
69
        lib.cmomentum_static_8bit_grad_32,
        lib.cmomentum_static_8bit_grad_16,
70
    )
Max Ryabinin's avatar
Max Ryabinin committed
71
72

    str2optimizer8bit_blockwise = {}
73
    str2optimizer8bit_blockwise["adam"] = (
74
75
76
        lib.cadam_8bit_blockwise_grad_fp32,
        lib.cadam_8bit_blockwise_grad_fp16,
        lib.cadam_8bit_blockwise_grad_bf16,
77
78
    )
    str2optimizer8bit_blockwise["momentum"] = (
79
80
        lib.cmomentum_8bit_blockwise_grad_fp32,
        lib.cmomentum_8bit_blockwise_grad_fp16,
81
82
    )
    str2optimizer8bit_blockwise["rmsprop"] = (
83
84
        lib.crmsprop_8bit_blockwise_grad_fp32,
        lib.crmsprop_8bit_blockwise_grad_fp16,
85
    )
86
    str2optimizer8bit_blockwise["lion"] = (
87
88
        lib.clion_8bit_blockwise_grad_fp32,
        lib.clion_8bit_blockwise_grad_fp16,
Tim Dettmers's avatar
Tim Dettmers committed
89
        lib.clion_8bit_blockwise_grad_bf16,
90
91
    )
    str2optimizer8bit_blockwise["adagrad"] = (
92
93
        lib.cadagrad_8bit_blockwise_grad_fp32,
        lib.cadagrad_8bit_blockwise_grad_fp16,
94
    )
Tim Dettmers's avatar
Tim Dettmers committed
95

Tim Dettmers's avatar
Tim Dettmers committed
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
class GlobalPageManager:
    _instance = None

    def __init__(self):
        raise RuntimeError("Call get_instance() instead")

    def initialize(self):
        self.paged_tensors = []

    @classmethod
    def get_instance(cls):
        if cls._instance is None:
            cls._instance = cls.__new__(cls)
            cls._instance.initialize()
        return cls._instance

    def prefetch_all(self, to_cpu=False):
Tim Dettmers's avatar
Tim Dettmers committed
113
114
115
116
        # assume the first added, will be hte
        # ones that are used first, so swap them in last
        # in the case they are evicted again
        for t in self.paged_tensors[::-1]:
Tim Dettmers's avatar
Tim Dettmers committed
117
118
119
            prefetch_tensor(t, to_cpu)


Tim Dettmers's avatar
Tim Dettmers committed
120

121
class CUBLAS_Context:
Tim Dettmers's avatar
Tim Dettmers committed
122
123
124
    _instance = None

    def __init__(self):
125
        raise RuntimeError("Call get_instance() instead")
Tim Dettmers's avatar
Tim Dettmers committed
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144

    def initialize(self):
        self.context = {}

    @classmethod
    def get_instance(cls):
        if cls._instance is None:
            cls._instance = cls.__new__(cls)
            cls._instance.initialize()
        return cls._instance

    def get_context(self, device):
        if device.index not in self.context:
            prev_device = torch.cuda.current_device()
            torch.cuda.set_device(device)
            self.context[device.index] = ct.c_void_p(lib.get_context())
            torch.cuda.set_device(prev_device)
        return self.context[device.index]

145

146
class Cusparse_Context:
Tim Dettmers's avatar
Tim Dettmers committed
147
148
149
    _instance = None

    def __init__(self):
150
        raise RuntimeError("Call get_instance() instead")
Tim Dettmers's avatar
Tim Dettmers committed
151
152
153
154
155
156
157
158
159
160

    def initialize(self):
        self.context = ct.c_void_p(lib.get_cusparse())

    @classmethod
    def get_instance(cls):
        if cls._instance is None:
            cls._instance = cls.__new__(cls)
            cls._instance.initialize()
        return cls._instance
Tim Dettmers's avatar
Tim Dettmers committed
161

Tim Dettmers's avatar
Tim Dettmers committed
162
163
164
165
166
167
168
169
170
171
172
173
dtype2bytes = {}
dtype2bytes[torch.float32] = 4
dtype2bytes[torch.float16] = 2
dtype2bytes[torch.bfloat16] = 2
dtype2bytes[torch.uint8] = 1
dtype2bytes[torch.int8] = 1

def get_paged(*shape, dtype=torch.float32, device=torch.device('cuda', index=0)):
    num_bytes = dtype2bytes[dtype]*prod(shape)
    cuda_ptr = lib.cget_managed_ptr(ct.c_size_t(num_bytes))
    c_ptr = ct.cast(cuda_ptr, ct.POINTER(ct.c_int))
    new_array = np.ctypeslib.as_array(c_ptr, shape=shape)
Tim Dettmers's avatar
Tim Dettmers committed
174
    out = torch.frombuffer(new_array, dtype=dtype, count=prod(shape)).view(shape)
Tim Dettmers's avatar
Tim Dettmers committed
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
    out.is_paged = True
    out.page_deviceid = device.index
    return out

def prefetch_tensor(A, to_cpu=False):
    assert A.is_paged, 'Only paged tensors can be prefetched!'
    if to_cpu:
        deviceid = -1
    else:
        deviceid = A.page_deviceid

    num_bytes = dtype2bytes[A.dtype]*A.numel()
    lib.cprefetch(get_ptr(A), ct.c_size_t(num_bytes), ct.c_int32(deviceid))

def elementwise_func(func_name, A, B, value, prefetch=True):
    func = None
    if A.dtype == torch.float32:
        func = getattr(lib, f'c{func_name}_fp32', None)
        cvalue = ct.c_float(value)
    elif A.dtype == torch.uint8:
        func = getattr(lib, f'c{func_name}_uint8', None)
        cvalue = ct.c_uint8(value)

    if func is None: raise NotImplementedError(f'Function not implemented: {func_name}')

    is_managed = getattr(A, 'is_managed', False)
    if is_managed and prefetch:
        prefetch_tensor(A)
        if B is not None: prefetch_tensor(B)

    func(get_ptr(A), get_ptr(B), cvalue, ct.c_int64(A.numel()))
    if A.is_paged or B.is_paged:
        # paged function are fully asynchronous
        # if we return from this function, we want to the tensor
        # to be in the correct state, that is the final state after the
        # operation occured. So we synchronize.
        torch.cuda.synchronize()

def fill(A, value, device=None, prefetch=True): elementwise_func('fill', A, None, value)
def arange(A, device=None): elementwise_func('arange', A, None, 0)
def _mul(A, B, device=None): elementwise_func('_mul', A, B, 0)

217

Tim Dettmers's avatar
Tim Dettmers committed
218
def create_linear_map(signed=True, total_bits=8, add_zero=True):
219
    sign = (-1.0 if signed else 0.0)
Tim Dettmers's avatar
Tim Dettmers committed
220
221
222
223
224
225
226
227
228
    total_values = 2**total_bits
    if add_zero or total_bits < 8:
        # add a zero
        # since we simulate less bits by having zeros in the data type, we
        # we need to center the quantization around zero and as such lose
        # a single value
        total_values = (2**total_bits if not signed else 2**total_bits-1)

    values = torch.linspace(sign, 1.0, total_values)
229
230
231
    gap = 256 - values.numel()
    if gap == 0:
        return values
Tim Dettmers's avatar
Tim Dettmers committed
232
    else:
233
234
        l = values.numel()//2
        return torch.Tensor(values[:l].tolist() + [0]*gap + values[l:].tolist())
Tim Dettmers's avatar
Tim Dettmers committed
235

236
def create_normal_map(offset=0.9677083, use_extra_value=True):
Tim Dettmers's avatar
Tim Dettmers committed
237
238
239
240
241
242
243
244
245
246

    if use_extra_value:
        # one more positive value, this is an asymmetric type
        v1 = norm.ppf(torch.linspace(offset, 0.5, 9)[:-1]).tolist()
        v2 = [0]*(256-15) ## we have 15 non-zero values in this data type
        v3 = (-norm.ppf(torch.linspace(offset, 0.5, 8)[:-1])).tolist()
    else:
        v1 = norm.ppf(torch.linspace(offset, 0.5, 8)[:-1]).tolist()
        v2 = [0]*(256-14) ## we have 14 non-zero values in this data type
        v3 = (-norm.ppf(torch.linspace(offset, 0.5, 8)[:-1])).tolist()
247
248

    v = v1 + v2 + v3
Tim Dettmers's avatar
Tim Dettmers committed
249
250
251
252

    values = torch.Tensor(v)
    values = values.sort().values
    values /= values.max()
253

Tim Dettmers's avatar
Tim Dettmers committed
254
    assert values.numel() == 256
255

Tim Dettmers's avatar
Tim Dettmers committed
256
257
    return values

Tim Dettmers's avatar
Tim Dettmers committed
258
def create_fp8_map(signed=True, exponent_bits=5, precision_bits=2, total_bits=8):
Tim Dettmers's avatar
Tim Dettmers committed
259
260
    e = exponent_bits
    p = precision_bits
Tim Dettmers's avatar
Tim Dettmers committed
261
262
    has_sign = 1 if signed else 0
    assert e+p == total_bits-has_sign
Tim Dettmers's avatar
Tim Dettmers committed
263
264
265
    # the exponent is biased to 2^(e-1) -1 == 0
    evalues = []
    pvalues = []
Tim Dettmers's avatar
Tim Dettmers committed
266
    for i, val in enumerate(range(-((2**(exponent_bits-has_sign))), 2**(exponent_bits-has_sign), 1)):
Tim Dettmers's avatar
Tim Dettmers committed
267
268
269
270
        evalues.append(2**val)


    values = []
Tim Dettmers's avatar
Tim Dettmers committed
271
272
    lst = list(itertools.product([0, 1], repeat=precision_bits))
    #for ev in evalues:
273
    bias = 2**(exponent_bits-1)
Tim Dettmers's avatar
Tim Dettmers committed
274
275
276
277
278
279
280
    for evalue in range(2**(exponent_bits)):
        for bit_pattern in lst:
            value = (1 if evalue != 0 else 0)
            for i, pval in enumerate(list(bit_pattern)):
                value += pval*(2**-(i+1))
            if evalue == 0:
                # subnormals
281
                value = value*2**-(bias)
Tim Dettmers's avatar
Tim Dettmers committed
282
283
            else:
                # normals
284
                value = value*2**-(evalue-bias-1)
Tim Dettmers's avatar
Tim Dettmers committed
285
            values.append(value)
Tim Dettmers's avatar
Tim Dettmers committed
286
            if signed:
Tim Dettmers's avatar
Tim Dettmers committed
287
288
289
290
291
                values.append(-value)


    assert len(values) == 2**total_bits
    values.sort()
Tim Dettmers's avatar
Tim Dettmers committed
292
293
294
295
    if total_bits < 8:
        gap = 256 - len(values)
        for i in range(gap):
            values.append(0)
Tim Dettmers's avatar
Tim Dettmers committed
296
297
    values.sort()
    code = torch.Tensor(values)
298
    code /= code.max()
Tim Dettmers's avatar
Tim Dettmers committed
299
300
301
302
303

    return code



Tim Dettmers's avatar
Tim Dettmers committed
304
def create_dynamic_map(signed=True, max_exponent_bits=7, total_bits=8):
305
    """
Tim Dettmers's avatar
Tim Dettmers committed
306
307
308
309
310
311
312
313
314
315
316
317
318
    Creates the dynamic quantiztion map.

    The dynamic data type is made up of a dynamic exponent and
    fraction. As the exponent increase from 0 to -7 the number
    of bits available for the fraction shrinks.

    This is a generalization of the dynamic type where a certain
    number of the bits and be reserved for the linear quantization
    region (the fraction). n determines the maximum number of
    exponent bits.

    For more details see
    (8-Bit Approximations for Parallelism in Deep Learning)[https://arxiv.org/abs/1511.04561]
319
    """
Tim Dettmers's avatar
Tim Dettmers committed
320
321
322
323
324

    data = []
    # these are additional items that come from the case
    # where all the exponent bits are zero and no
    # indicator bit is present
325
    non_sign_bits = total_bits - (1 if signed else 1)
Tim Dettmers's avatar
Tim Dettmers committed
326
327
328
    additional_items = 2 ** (non_sign_bits - max_exponent_bits) - 1
    for i in range(max_exponent_bits):
        fraction_items = int((2 ** (i + non_sign_bits - max_exponent_bits) + 1 if signed else 2 ** (i + non_sign_bits - max_exponent_bits + 1) + 1))
Tim Dettmers's avatar
Tim Dettmers committed
329
        boundaries = torch.linspace(0.1, 1, fraction_items)
330
        means = (boundaries[:-1] + boundaries[1:]) / 2.0
Tim Dettmers's avatar
Tim Dettmers committed
331
        data += ((10 ** (-(max_exponent_bits - 1) + i)) * means).tolist()
Tim Dettmers's avatar
Tim Dettmers committed
332
        if signed:
Tim Dettmers's avatar
Tim Dettmers committed
333
            data += (-(10 ** (-(max_exponent_bits - 1) + i)) * means).tolist()
Tim Dettmers's avatar
Tim Dettmers committed
334

335
336
337
338
339
340
    if additional_items > 0:
        boundaries = torch.linspace(0.1, 1, additional_items + 1)
        means = (boundaries[:-1] + boundaries[1:]) / 2.0
        data += ((10 ** (-(max_exponent_bits - 1) + i)) * means).tolist()
        if signed:
            data += (-(10 ** (-(max_exponent_bits - 1) + i)) * means).tolist()
Tim Dettmers's avatar
Tim Dettmers committed
341
342
343

    data.append(0)
    data.append(1.0)
Tim Dettmers's avatar
Tim Dettmers committed
344

345
346
    assert len(data) == 2**total_bits

Tim Dettmers's avatar
Tim Dettmers committed
347
348
349
350
    gap = 256 - len(data)
    for i in range(gap):
        data.append(0)

Tim Dettmers's avatar
Tim Dettmers committed
351
352
353
    data.sort()
    return Tensor(data)

Tim Dettmers's avatar
Tim Dettmers committed
354
355
356
357
358
359
360
361
362
363
364
365
366
367
def create_quantile_map(A, total_bits=8):
    q = estimate_quantiles(A, num_quantiles=2**total_bits-1)
    q = q.tolist()
    q.append(0)

    gap = 256 - len(q)
    for i in range(gap):
        q.append(0)

    q.sort()

    q = Tensor(q)
    q = q/q.abs().max()
    return q
368

Tim Dettmers's avatar
Tim Dettmers committed
369
def get_special_format_str():
370
    if not torch.cuda.is_available(): return 'col_turing'
Tom Aarsen's avatar
Tom Aarsen committed
371
    major, _minor = torch.cuda.get_device_capability()
372
    if major <= 7:
373
        return "col_turing"
Tom Aarsen's avatar
Tom Aarsen committed
374
    if major == 8:
375
        return "col_ampere"
Tom Aarsen's avatar
Tom Aarsen committed
376
    return "col_turing"
377

Tim Dettmers's avatar
Tim Dettmers committed
378

379
380
381

def is_on_gpu(tensors):
    on_gpu = True
382
    gpu_ids = set()
383
384
    for t in tensors:
        if t is None: continue # NULL pointers are fine
Tim Dettmers's avatar
Tim Dettmers committed
385
386
387
388
389
390
        is_paged = getattr(t, 'is_paged', False)
        on_gpu &= (t.device.type == 'cuda' or is_paged)
        if not is_paged:
            gpu_ids.add(t.device.index)
    if not on_gpu:
        raise TypeError(f'All input tensors need to be on the same GPU, but found some tensors to not be on a GPU:\n {[(t.shape, t.device) for t in tensors]}')
391
    if len(gpu_ids) > 1:
Tim Dettmers's avatar
Tim Dettmers committed
392
        raise TypeError(f'Input tensors need to be on the same GPU, but found the following tensor and device combinations:\n {[(t.shape, t.device) for t in tensors]}')
393
394
    return on_gpu

Tim Dettmers's avatar
Tim Dettmers committed
395
def get_ptr(A: Tensor) -> ct.c_void_p:
396
    """
Tim Dettmers's avatar
Tim Dettmers committed
397
398
399
400
401
402
403
404
405
406
    Get the ctypes pointer from a PyTorch Tensor.

    Parameters
    ----------
    A : torch.tensor
        The PyTorch tensor.

    Returns
    -------
    ctypes.c_void_p
407
408
409
410
    """
    if A is None:
        return None
    else:
411
        return ct.c_void_p(A.data.data_ptr())
412

Tim Dettmers's avatar
Tim Dettmers committed
413

Tim Dettmers's avatar
Tim Dettmers committed
414
415
416
417
418
def pre_call(device):
    prev_device = torch.cuda.current_device()
    torch.cuda.set_device(device)
    return prev_device

419

Tim Dettmers's avatar
Tim Dettmers committed
420
421
422
def post_call(prev_device):
    torch.cuda.set_device(prev_device)

423

Tim Dettmers's avatar
Tim Dettmers committed
424
425
426
427
def get_transform_func(dtype, orderA, orderOut, transpose=False):
    name = f'ctransform_{(8 if dtype == torch.int8 else 32)}_{orderA}_to_{orderOut}_{"t" if transpose else "n"}'
    if not hasattr(lib, name):
        print(name)
428
429
430
        raise ValueError(
            f"Transform function not supported: {orderA} to {orderOut} for data type {dtype} and transpose={transpose}"
        )
Tim Dettmers's avatar
Tim Dettmers committed
431
432
433
    else:
        return getattr(lib, name)

434
435
436
437
438

def get_transform_buffer(
    shape, dtype, device, to_order, from_order="row", transpose=False
):
    # init_func = torch.empty
Tim Dettmers's avatar
Tim Dettmers committed
439
440
441
442
443
444
    init_func = torch.zeros
    dims = len(shape)

    if dims == 2:
        rows = shape[0]
    elif dims == 3:
445
        rows = shape[0] * shape[1]
Tim Dettmers's avatar
Tim Dettmers committed
446
447
448
449
450
451
452
453
454
455
    cols = shape[-1]

    state = (shape, to_order)
    if transpose:
        # swap dims
        tmp = rows
        rows = cols
        cols = tmp
        state = (shape[::-1], to_order)

456
    if to_order == "row" or to_order == "col":
Tim Dettmers's avatar
Tim Dettmers committed
457
        return init_func(shape, dtype=dtype, device=device), state
458
    elif to_order == "col32":
Tim Dettmers's avatar
Tim Dettmers committed
459
        # blocks of 32 columns (padded)
460
        cols = 32 * ((cols + 31) // 32)
Tim Dettmers's avatar
Tim Dettmers committed
461
        return init_func((rows, cols), dtype=dtype, device=device), state
462
    elif to_order == "col_turing":
Tim Dettmers's avatar
Tim Dettmers committed
463
        # blocks of 32 columns and 8 rows
464
465
        cols = 32 * ((cols + 31) // 32)
        rows = 8 * ((rows + 7) // 8)
Tim Dettmers's avatar
Tim Dettmers committed
466
        return init_func((rows, cols), dtype=dtype, device=device), state
467
    elif to_order == "col_ampere":
Tim Dettmers's avatar
Tim Dettmers committed
468
        # blocks of 32 columns and 32 rows
469
470
        cols = 32 * ((cols + 31) // 32)
        rows = 32 * ((rows + 31) // 32)
Tim Dettmers's avatar
Tim Dettmers committed
471
472
        return init_func((rows, cols), dtype=dtype, device=device), state
    else:
473
474
        raise NotImplementedError(f"To_order not supported: {to_order}")

Tim Dettmers's avatar
Tim Dettmers committed
475

476
def nvidia_transform(
477
478
479
480
481
482
483
    A,
    to_order,
    from_order="row",
    out=None,
    transpose=False,
    state=None,
    ld=None,
484
485
486
487
488
489
490
491
492
493
494
):
    if state is None:
        state = (A.shape, from_order)
    else:
        from_order = state[1]
    if out is None:
        out, new_state = get_transform_buffer(
            state[0], A.dtype, A.device, to_order, state[1]
        )
    else:
        new_state = (state[1], to_order)
Tim Dettmers's avatar
Tim Dettmers committed
495
496
497
498
499
500
501
    func = get_transform_func(A.dtype, from_order, to_order, transpose)

    shape = state[0]
    if len(shape) == 2:
        dim1 = ct.c_int32(shape[0])
        dim2 = ct.c_int32(shape[1])
    elif ld is not None:
502
503
        n = prod(shape)
        dim1 = prod([shape[i] for i in ld])
504
        dim2 = ct.c_int32(n // dim1)
Tim Dettmers's avatar
Tim Dettmers committed
505
506
        dim1 = ct.c_int32(dim1)
    else:
507
        dim1 = ct.c_int32(shape[0] * shape[1])
Tim Dettmers's avatar
Tim Dettmers committed
508
509
510
511
512
513
514
        dim2 = ct.c_int32(shape[2])

    ptr = CUBLAS_Context.get_instance().get_context(A.device)
    func(ptr, get_ptr(A), get_ptr(out), dim1, dim2)

    return out, new_state

515

Tim Dettmers's avatar
Tim Dettmers committed
516
def estimate_quantiles(A: Tensor, out: Tensor = None, offset: float = 1 / 512, num_quantiles=256) -> Tensor:
Tim Dettmers's avatar
Tim Dettmers committed
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
    '''
    Estimates 256 equidistant quantiles on the input tensor eCDF.

    Uses SRAM-Quantiles algorithm to quickly estimate 256 equidistant quantiles
    via the eCDF of the input tensor `A`. This is a fast but approximate algorithm
    and the extreme quantiles close to 0 and 1 have high variance / large estimation
    errors. These large errors can be avoided by using the offset variable which trims
    the distribution. The default offset value of 1/512 ensures minimum entropy encoding -- it
    trims 1/512 = 0.2% from each side of the distrivution. An offset value of 0.01 to 0.02
    usually has a much lower error but is not a minimum entropy encoding. Given an offset
    of 0.02 equidistance points in the range [0.02, 0.98] are used for the quantiles.

    Parameters
    ----------
    A : torch.Tensor
        The input tensor. Any shape.
    out : torch.Tensor
        Tensor with the 256 estimated quantiles.
    offset : float
Tim Dettmers's avatar
Tim Dettmers committed
536
537
538
        The offset for the first and last quantile from 0 and 1. Default: 1/(2*num_quantiles)
    num_quantiles : int
        The number of equally spaced quantiles.
Tim Dettmers's avatar
Tim Dettmers committed
539
540
541
542
543
544

    Returns
    -------
    torch.Tensor:
        The 256 quantiles in float32 datatype.
    '''
Tim Dettmers's avatar
Tim Dettmers committed
545
546
547
548
549
550
    if A.numel() < 256: raise NotImplementedError(f'Quantile estimation needs at least 256 values in the Tensor, but Tensor had only {A.numel()} values.')
    if num_quantiles > 256: raise NotImplementedError(f"Currently only a maximum of 256 equally spaced quantiles are supported, but the argument num_quantiles={num_quantiles}")
    if num_quantiles < 256 and offset == 1/(512):
        # override default arguments
        offset = 1/(2*num_quantiles)

Tim Dettmers's avatar
Tim Dettmers committed
551
    if out is None: out = torch.zeros((256,), dtype=torch.float32, device=A.device)
552
    is_on_gpu([A, out])
Tim Dettmers's avatar
Tim Dettmers committed
553
    device = pre_call(A.device)
Tim Dettmers's avatar
Tim Dettmers committed
554
    if A.dtype == torch.float32:
Tim Dettmers's avatar
Tim Dettmers committed
555
        lib.cestimate_quantiles_fp32(get_ptr(A), get_ptr(out), ct.c_float(offset), ct.c_int(A.numel()))
Tim Dettmers's avatar
Tim Dettmers committed
556
    elif A.dtype == torch.float16:
Tim Dettmers's avatar
Tim Dettmers committed
557
        lib.cestimate_quantiles_fp16(get_ptr(A), get_ptr(out), ct.c_float(offset), ct.c_int(A.numel()))
Tim Dettmers's avatar
Tim Dettmers committed
558
    else:
559
        raise NotImplementedError(f"Not supported data type {A.dtype}")
Tim Dettmers's avatar
Tim Dettmers committed
560
561
562
    post_call(device)

    if num_quantiles < 256:
Tim Dettmers's avatar
Tim Dettmers committed
563
        step = round(256/num_quantiles)
Tim Dettmers's avatar
Tim Dettmers committed
564
565
566
        idx = torch.linspace(0, 255, num_quantiles).long().to(A.device)
        out = out[idx]

Tim Dettmers's avatar
Tim Dettmers committed
567
568
    return out

569
570
571
572
573
574
575
576
577
578
579
580
class QuantState:
    def __init__(self, absmax, shape=None, code=None, blocksize=None, quant_type=None, dtype=None, offset=None, state2=None):
        self.absmax = absmax
        self.shape = shape
        self.code = code
        self.dtype = dtype
        self.blocksize = blocksize
        self.quant_type = quant_type
        self.offset = offset
        self.state2 = state2
        self.nested = state2 is not None

Ruslan Svirschevski's avatar
Ruslan Svirschevski committed
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
    @classmethod
    def from_kwargs(cls, kwargs, device):

        tensor2str = lambda xx: ''.join([chr(x) for x in xx]).strip('.')

        kwargs = {k.split('.')[-1] :v for k, v in kwargs.items()}
        
        if 'nested_absmax' in kwargs:
            offset = kwargs['nested_offset']
            state2 = cls(
                absmax=kwargs['nested_absmax'].to(device),
                code=kwargs['nested_code'].to(device),
                blocksize=kwargs['nested_blocksize'].item(),
                dtype=getattr(torch, tensor2str(kwargs['nested_dtype'])),
            )
        else:
            offset, state2 = None, None

        quant_state = cls(
            absmax=kwargs['absmax'].to(device), 
            shape=torch.Size(kwargs['shape']),
            dtype=getattr(torch, tensor2str(kwargs['dtype'])),
            blocksize=kwargs['blocksize'].item(),
            offset=offset,
            state2=state2,
            quant_type=tensor2str(kwargs['quant_type']),
            code=kwargs['code'].to(device),
        )
        return quant_state

611
612
613
614
615
616
617
    def to(self, device):
        # make sure the quantization state is on the right device
        self.absmax = self.absmax.to(device)
        if self.nested:
            self.offset = self.offset.to(device)
            self.state2.absmax = self.state2.absmax.to(device)
            self.state2.code = self.state2.code.to(device)
618

619
def quantize_blockwise(A: Tensor, code: Tensor = None, absmax: Tensor = None, out: Tensor = None, blocksize=4096, nested=False) -> Tensor:
620
    """
Tim Dettmers's avatar
Tim Dettmers committed
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
    Quantize tensor A in blocks of size 4096 values.

    Quantizes tensor A by dividing it into blocks of 4096 values.
    Then the absolute maximum value within these blocks is calculated
    for the non-linear quantization.

    Parameters
    ----------
    A : torch.Tensor
        The input tensor.
    code : torch.Tensor
        The quantization map.
    absmax : torch.Tensor
        The absmax values.
    out : torch.Tensor
        The output tensor (8-bit).

    Returns
    -------
    torch.Tensor:
        The 8-bit tensor.
    tuple(torch.Tensor, torch.Tensor):
        The quantization state to undo the quantization.
644
    """
Tim Dettmers's avatar
Tim Dettmers committed
645

646

Tim Dettmers's avatar
Tim Dettmers committed
647
    if code is None:
648
649
650
        if "dynamic" not in name2qmap:
            name2qmap["dynamic"] = create_dynamic_map().to(A.device)
        code = name2qmap["dynamic"]
Tim Dettmers's avatar
Tim Dettmers committed
651
652
653

    if absmax is None:
        n = A.numel()
654
655
        blocks = n // blocksize
        blocks += 1 if n % blocksize > 0 else 0
656
        absmax = torch.zeros((blocks,), device=A.device, dtype=torch.float32)
Tim Dettmers's avatar
Tim Dettmers committed
657

658
659
    if out is None:
        out = torch.zeros_like(A, dtype=torch.uint8)
Tim Dettmers's avatar
Tim Dettmers committed
660
661

    if A.device.type != 'cpu':
662
        assert blocksize in [4096, 2048, 1024, 512, 256, 128, 64]
663
        cblocksize = ct.c_int32(blocksize)
664
665
        prev_device = pre_call(A.device)
        code = code.to(A.device)
666
667
668
669
670
        is_on_gpu([code, A, out, absmax])
        if A.dtype == torch.float32:
            lib.cquantize_blockwise_fp32(get_ptr(code), get_ptr(A), get_ptr(absmax), get_ptr(out), cblocksize, ct.c_int(A.numel()))
        elif A.dtype == torch.float16:
            lib.cquantize_blockwise_fp16(get_ptr(code), get_ptr(A), get_ptr(absmax), get_ptr(out), cblocksize, ct.c_int(A.numel()))
671
672
        elif A.dtype == torch.bfloat16:
            lib.cquantize_blockwise_bf16(get_ptr(code), get_ptr(A), get_ptr(absmax), get_ptr(out), cblocksize, ct.c_int(A.numel()))
Tim Dettmers's avatar
Tim Dettmers committed
673
        else:
674
            raise ValueError(f"Blockwise quantization only supports 16/32-bit floats, but got {A.dtype}")
675
        post_call(A.device)
Tim Dettmers's avatar
Tim Dettmers committed
676
677
    else:
        # cpu
678
        code = code.cpu()
679
        lib.cquantize_blockwise_cpu_fp32(get_ptr(code), get_ptr(A), get_ptr(absmax), get_ptr(out), ct.c_longlong(blocksize), ct.c_longlong(A.numel()))
Tim Dettmers's avatar
Tim Dettmers committed
680

681
682
683
684
    if nested:
        offset = absmax.mean()
        absmax -= offset
        qabsmax, state2 = quantize_blockwise(absmax, blocksize=blocksize, nested=False)
685
        quant_state = QuantState(absmax=qabsmax, code=code, blocksize=blocksize, dtype=A.dtype, offset=offset, state2=state2)
686
    else:
687
        quant_state = QuantState(absmax=absmax, code=code, blocksize=blocksize, dtype=A.dtype)
688

689
    return out, quant_state
Tim Dettmers's avatar
Tim Dettmers committed
690

691
692
693

def dequantize_blockwise(
    A: Tensor,
694
    quant_state: QuantState = None,
695
696
697
698
    absmax: Tensor = None,
    code: Tensor = None,
    out: Tensor = None,
    blocksize: int = 4096,
699
    nested=False
700
701
) -> Tensor:
    """
Tim Dettmers's avatar
Tim Dettmers committed
702
703
704
705
706
707
708
709
710
    Dequantizes blockwise quantized values.

    Dequantizes the tensor A with maximum absolute values absmax in
    blocks of size 4096.

    Parameters
    ----------
    A : torch.Tensor
        The input 8-bit tensor.
711
712
    quant_state : QuantState
        Object with code, absmax and other quantization state components.
Tim Dettmers's avatar
Tim Dettmers committed
713
714
715
716
717
718
719
720
721
722
723
724
    absmax : torch.Tensor
        The absmax values.
    code : torch.Tensor
        The quantization map.
    out : torch.Tensor
        Dequantized output tensor (default: float32)


    Returns
    -------
    torch.Tensor:
        Dequantized tensor (default: float32)
725
    """
Tim Dettmers's avatar
Tim Dettmers committed
726
727
    assert quant_state is not None or absmax is not None
    if code is None and quant_state is None:
728
729
730
        if "dynamic" not in name2qmap:
            name2qmap["dynamic"] = create_dynamic_map().to(A.device)
        code = name2qmap["dynamic"]
Tim Dettmers's avatar
Tim Dettmers committed
731

732
    if quant_state is None:
733
734
735
736
737
738
       quant_state = QuantState(absmax=absmax, code=code, blocksize=blocksize, dtype=torch.float32)
    
    absmax = quant_state.absmax
    if quant_state.nested:
        absmax = dequantize_blockwise(quant_state.absmax, quant_state.state2)
        absmax += quant_state.offset
739
        if absmax.dtype != torch.float32: absmax = absmax.float()
Tim Dettmers's avatar
Tim Dettmers committed
740

741
    if out is None:
742
        out = torch.empty(A.shape, dtype=quant_state.dtype, device=A.device)
Tim Dettmers's avatar
Tim Dettmers committed
743
744

    if A.device.type != 'cpu':
745
        device = pre_call(A.device)
746
747
748
        code = quant_state.code.to(A.device)
        if quant_state.blocksize not in [2048, 4096, 1024, 512, 256, 128, 64]:
            raise ValueError(f"The blockwise of {quant_state.blocksize} is not supported. Supported values: [2048, 4096, 1024, 512, 256, 128, 64]")
749
        is_on_gpu([A, absmax, out])
Tim Dettmers's avatar
Tim Dettmers committed
750
        if out.dtype == torch.float32:
751
            lib.cdequantize_blockwise_fp32(get_ptr(quant_state.code), get_ptr(A), get_ptr(absmax), get_ptr(out), ct.c_int(quant_state.blocksize), ct.c_int(A.numel()))
Tim Dettmers's avatar
Tim Dettmers committed
752
        elif out.dtype == torch.float16:
753
            lib.cdequantize_blockwise_fp16(get_ptr(quant_state.code), get_ptr(A), get_ptr(absmax), get_ptr(out), ct.c_int(quant_state.blocksize), ct.c_int(A.numel()))
754
        elif out.dtype == torch.bfloat16:
755
            lib.cdequantize_blockwise_bf16(get_ptr(quant_state.code), get_ptr(A), get_ptr(absmax), get_ptr(out), ct.c_int(quant_state.blocksize), ct.c_int(A.numel()))
Tim Dettmers's avatar
Tim Dettmers committed
756
        else:
Tim Dettmers's avatar
Tim Dettmers committed
757
            raise ValueError(f"Blockwise quantization only supports 16/32-bit floats, but got {A.dtype}")
758
        post_call(A.device)
Tim Dettmers's avatar
Tim Dettmers committed
759
    else:
760
761
        code = quant_state.code.cpu()
        lib.cdequantize_blockwise_cpu_fp32(get_ptr(code), get_ptr(A), get_ptr(quant_state.absmax), get_ptr(out), ct.c_longlong(quant_state.blocksize), ct.c_longlong(A.numel()))
Tim Dettmers's avatar
Tim Dettmers committed
762
763
764

    return out

765
766
767
768
def get_4bit_type(typename, device=None, blocksize=64):
    if device is None: device = 'cuda'
    data = None
    if typename == 'nf4':
769
770
771
772
773
774
775
776
777
778
        ''' Implements the NF4 data type.

            Constructs a quantization data type where each bin has equal area under a standard normal distribution N(0, 1) that
            is normalized into the range [-1, 1].

            For more information read the paper: QLoRA: Efficient Finetuning of Quantized LLMs (https://arxiv.org/abs/2305.14314)

            Implementation of the NF4 data type in bitsandbytes can be found in the `create_normal_map` function in
            the `functional.py` file: https://github.com/TimDettmers/bitsandbytes/blob/main/bitsandbytes/functional.py#L236.
        '''
779
780
781
782
783
784
785
786
787
788
789
790
791
        data = [-1.0, -0.6961928009986877, -0.5250730514526367, -0.39491748809814453, -0.28444138169288635,
                -0.18477343022823334, -0.09105003625154495, 0.0, 0.07958029955625534, 0.16093020141124725,
                0.24611230194568634, 0.33791524171829224, 0.44070982933044434, 0.5626170039176941,
                0.7229568362236023, 1.0]
    elif typename == 'fp4':
        # 0b000 = 0
        # 0b001 = 0.0625
        # 0b010 = 8
        # 0b011 = 12
        # 0b100 = 4
        # 0b101 = 6
        # 0b110 = 2
        # 0b111 = 3
792
        # can also be created with bnb.functional.create_fp8_map(signed=True, exponent_bits=2, precision_bits=1, total_bits=4)
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
        data = [0, 0.0625, 8.0, 12.0, 4.0, 6.0, 2.0, 3.0, -0, -0.0625, -8.0, -12.0, -4.0, -6.0, -2.0, -3.0]
    elif typename == 'int4':
        data = [7, 6, 5, 4, 3, 2, 1, 0, -0, -1, -2, -3, -4, -5, -6, -7]
    elif typename == 'af4':
        # Taken from: NF4 Isn't Information Theoretically Optimal (and that's Good)
        # https://arxiv.org/abs/2306.06965
        if blocksize == 64:
            data = [-1., -0.69441008, -0.51243739, -0.3736951, -0.25607552, -0.14982478,
                    -0.04934812,  0., 0.04273164, 0.12934483, 0.21961274, 0.31675666,
                    0.42563882,  0.55496234,  0.72424863,  1.][::-1]
        else:
            raise NotImplementedError(f'4-bit AbnormalFloats currently only support blocksize 64.')

    if data is None:
        raise NotImplementedError(f'Typename {typename} not supported')

    data = Tensor(data)
    data /= data.abs().max()
    assert data.numel() == 16

    return data.to(device)



Tim Dettmers's avatar
Tim Dettmers committed
817
def quantize_fp4(A: Tensor, absmax: Tensor = None, out: Tensor = None, blocksize=64, compress_statistics=False):
818
    return quantize_4bit(A, absmax, out, blocksize, compress_statistics, 'fp4')
Tim Dettmers's avatar
Tim Dettmers committed
819

Tim Dettmers's avatar
Tim Dettmers committed
820
def quantize_nf4(A: Tensor, absmax: Tensor = None, out: Tensor = None, blocksize=64, compress_statistics=False):
821
    return quantize_4bit(A, absmax, out, blocksize, compress_statistics, 'nf4')
Tim Dettmers's avatar
Tim Dettmers committed
822

823
def quantize_4bit(A: Tensor, absmax: Tensor = None, out: Tensor = None, blocksize=64, compress_statistics=False, quant_type='fp4') -> Tensor:
824
    """
825
    Quantize tensor A in blocks of 4-bit values.
826
827
828
829
830
831
832
833
834
835
836
837
838

    Quantizes tensor A by dividing it into blocks which are independently quantized to FP4.

    Parameters
    ----------
    A : torch.Tensor
        The input tensor.
    absmax : torch.Tensor
        The absmax values.
    out : torch.Tensor
        The output tensor (8-bit).
    blocksize : int
        The blocksize used in quantization.
Tim Dettmers's avatar
Tim Dettmers committed
839
840
    quant_type : str
        The 4-bit quantization data type {fp4, nf4}
841
842
843
844
845

    Returns
    -------
    torch.Tensor:
        The 8-bit tensor with packed 4-bit values.
Tim Dettmers's avatar
Tim Dettmers committed
846
    tuple(torch.Tensor, torch.Size, torch.dtype, int):
847
848
849
850
        The quantization state to undo the quantization.
    """
    if A.device.type != 'cuda':
        raise NotImplementedError(f'Device type not supported for FP4 quantization: {A.device.type}')
Tim Dettmers's avatar
Tim Dettmers committed
851
852
    if quant_type not in ['fp4', 'nf4']:
        raise NotImplementedError(f'4-bit quantization data type {quant_type} is not implemented.')
853
854
855
856
857
858
859

    n = A.numel()
    input_shape = A.shape

    if absmax is None:
        blocks = n // blocksize
        blocks += 1 if n % blocksize > 0 else 0
860
        absmax = torch.zeros((blocks,), device=A.device, dtype=torch.float32)
861
862
863


    if out is None:
Tim Dettmers's avatar
Tim Dettmers committed
864
        out = torch.zeros(((n+1)//2, 1), dtype=torch.uint8, device=A.device)
865

866
    assert blocksize in [4096, 2048, 1024, 512, 256, 128, 64]
867
868
869
870
871

    prev_device = pre_call(A.device)
    is_on_gpu([A, out, absmax])

    if A.dtype == torch.float32:
Tim Dettmers's avatar
Tim Dettmers committed
872
873
874
875
        if quant_type == 'fp4':
            lib.cquantize_blockwise_fp32_fp4(get_ptr(None), get_ptr(A), get_ptr(absmax), get_ptr(out), ct.c_int32(blocksize), ct.c_int(n))
        else:
            lib.cquantize_blockwise_fp32_nf4(get_ptr(None), get_ptr(A), get_ptr(absmax), get_ptr(out), ct.c_int32(blocksize), ct.c_int(n))
876
    elif A.dtype == torch.float16:
Tim Dettmers's avatar
Tim Dettmers committed
877
878
879
880
        if quant_type == 'fp4':
            lib.cquantize_blockwise_fp16_fp4(get_ptr(None), get_ptr(A), get_ptr(absmax), get_ptr(out), ct.c_int32(blocksize), ct.c_int(n))
        else:
            lib.cquantize_blockwise_fp16_nf4(get_ptr(None), get_ptr(A), get_ptr(absmax), get_ptr(out), ct.c_int32(blocksize), ct.c_int(n))
881
882
883
884
885
    elif A.dtype == torch.bfloat16:
        if quant_type == 'fp4':
            lib.cquantize_blockwise_bf16_fp4(get_ptr(None), get_ptr(A), get_ptr(absmax), get_ptr(out), ct.c_int32(blocksize), ct.c_int(n))
        else:
            lib.cquantize_blockwise_bf16_nf4(get_ptr(None), get_ptr(A), get_ptr(absmax), get_ptr(out), ct.c_int32(blocksize), ct.c_int(n))
886
887
888
889
    else:
        raise ValueError(f"Blockwise quantization only supports 16/32-bit floats, but got {A.dtype}")
    post_call(A.device)

890
    code = get_4bit_type(quant_type, device=A.device)
891

892
893
894
895
896
    if compress_statistics:
        offset = absmax.mean()
        absmax -= offset
        qabsmax, state2 = quantize_blockwise(absmax, blocksize=256)
        del absmax
897
        state = QuantState(absmax=qabsmax, shape=input_shape, dtype=A.dtype, blocksize=blocksize, code=code, quant_type=quant_type, offset=offset, state2=state2)
898
    else:
899
        state = QuantState(absmax=absmax, shape=input_shape, dtype=A.dtype, blocksize=blocksize, code=code, quant_type=quant_type, )
900

901
902
    return out, state

903
def dequantize_fp4(A: Tensor, quant_state: QuantState = None, absmax: Tensor = None, out: Tensor = None, blocksize: int = 64) -> Tensor:
904
    return dequantize_4bit(A, quant_state, absmax, out, blocksize, 'fp4')
Tim Dettmers's avatar
Tim Dettmers committed
905

906
def dequantize_nf4(A: Tensor, quant_state: QuantState = None, absmax: Tensor = None, out: Tensor = None, blocksize: int = 64) -> Tensor:
907
    return dequantize_4bit(A, quant_state, absmax, out, blocksize, 'nf4')
908

909
def dequantize_4bit(A: Tensor, quant_state: QuantState = None, absmax: Tensor = None, out: Tensor = None, blocksize: int = 64, quant_type='fp4') -> Tensor:
910
911
912
913
914
915
916
917
918
    """
    Dequantizes FP4 blockwise quantized values.

    Dequantizes the tensor A with maximum absolute values absmax in blocks of size blocksize.

    Parameters
    ----------
    A : torch.Tensor
        The input 8-bit tensor (packed 4-bit values).
919
920
    quant_state : QuantState
        object with quantisation stats, incl. absmax values, original tensor shape and original dtype.
921
922
923
924
    absmax : torch.Tensor
        The absmax values.
    out : torch.Tensor
        Dequantized output tensor.
Tim Dettmers's avatar
Tim Dettmers committed
925
926
927
928
    blocksize : int
        The blocksize used in quantization.
    quant_type : str
        The 4-bit quantization data type {fp4, nf4}
929
930
931
932
933
934
935
936
937


    Returns
    -------
    torch.Tensor:
        Dequantized tensor.
    """
    if blocksize not in [2048, 4096, 1024, 512, 256, 128, 64]:
        raise ValueError(f"The blockwise of {blocksize} is not supported. Supported values: [2048, 4096, 1024, 512, 256, 128, 64]")
Tim Dettmers's avatar
Tim Dettmers committed
938
939
    if quant_type not in ['fp4', 'nf4']:
        raise NotImplementedError(f'4-bit quantization data type {quant_type} is not implemented.')
940
941
942

    if quant_state is None:
        assert absmax is not None and out is not None
943
944
945

        quant_state = QuantState(absmax=absmax, shape=out.shape, dtype=out.dtype, blocksize=blocksize, quant_type=quant_type)

946
    else:
947
        absmax = quant_state.absmax
948

949

950
951
952
    if quant_state.nested:
        absmax = dequantize_blockwise(quant_state.absmax, quant_state.state2)
        absmax += quant_state.offset
953
        if absmax.dtype != torch.float32: absmax = absmax.float()
954
955

    if out is None:
956
        out = torch.empty(quant_state.shape, dtype=quant_state.dtype, device=A.device)
957
958
959
960
961
962

    n = out.numel()

    device = pre_call(A.device)
    is_on_gpu([A, absmax, out])
    if out.dtype == torch.float32:
963
964
        if quant_state.quant_type == 'fp4':
            lib.cdequantize_blockwise_fp32_fp4(get_ptr(None), get_ptr(A), get_ptr(absmax), get_ptr(out), ct.c_int(quant_state.blocksize), ct.c_int(n))
Tim Dettmers's avatar
Tim Dettmers committed
965
        else:
966
            lib.cdequantize_blockwise_fp32_nf4(get_ptr(None), get_ptr(A), get_ptr(absmax), get_ptr(out), ct.c_int(quant_state.blocksize), ct.c_int(n))
967
    elif out.dtype == torch.float16:
968
969
        if quant_state.quant_type == 'fp4':
            lib.cdequantize_blockwise_fp16_fp4(get_ptr(None), get_ptr(A), get_ptr(absmax), get_ptr(out), ct.c_int(quant_state.blocksize), ct.c_int(n))
Tim Dettmers's avatar
Tim Dettmers committed
970
        else:
971
            lib.cdequantize_blockwise_fp16_nf4(get_ptr(None), get_ptr(A), get_ptr(absmax), get_ptr(out), ct.c_int(quant_state.blocksize), ct.c_int(n))
972
    elif out.dtype == torch.bfloat16:
973
974
        if quant_state.quant_type == 'fp4':
            lib.cdequantize_blockwise_bf16_fp4(get_ptr(None), get_ptr(A), get_ptr(absmax), get_ptr(out), ct.c_int(quant_state.blocksize), ct.c_int(n))
975
        else:
976
            lib.cdequantize_blockwise_bf16_nf4(get_ptr(None), get_ptr(A), get_ptr(absmax), get_ptr(out), ct.c_int(quant_state.blocksize), ct.c_int(n))
977
978
979
980
    else:
        raise ValueError(f"Blockwise quantization only supports 16/32-bit floats, but got {A.dtype}")
    post_call(A.device)

Tim Dettmers's avatar
Tim Dettmers committed
981
982
983
    is_transposed = (True if A.shape[0] == 1 else False)
    if is_transposed: return out.t()
    else: return out
984
985


986
def quantize(A: Tensor, code: Tensor = None, out: Tensor = None) -> Tensor:
Tim Dettmers's avatar
Tim Dettmers committed
987
    if code is None:
988
989
990
        if "dynamic" not in name2qmap:
            name2qmap["dynamic"] = create_dynamic_map().to(A.device)
        code = name2qmap["dynamic"]
Tim Dettmers's avatar
Tim Dettmers committed
991
992
993
        code = code.to(A.device)

    absmax = torch.abs(A).max()
994
    if absmax.dtype != torch.float32: absmax = absmax.float()
995
    inp = A / absmax
Tim Dettmers's avatar
Tim Dettmers committed
996
997
998
    out = quantize_no_absmax(inp, code, out)
    return out, (absmax, code)

999
1000
1001

def dequantize(
    A: Tensor,
1002
    state: Tuple[Tensor, Tensor] = None,
1003
1004
1005
1006
    absmax: Tensor = None,
    code: Tensor = None,
    out: Tensor = None,
) -> Tensor:
1007
1008
    assert state is not None or absmax is not None
    if code is None and state is None:
1009
1010
1011
        if "dynamic" not in name2qmap:
            name2qmap["dynamic"] = create_dynamic_map().to(A.device)
        code = name2qmap["dynamic"]
Tim Dettmers's avatar
Tim Dettmers committed
1012
1013
        code = code.to(A.device)

1014
1015
1016
1017
    if state is None:
        state = (absmax, code)
    out = dequantize_no_absmax(A, state[1], out)
    return out * state[0]
Tim Dettmers's avatar
Tim Dettmers committed
1018

1019
1020

def quantize_no_absmax(A: Tensor, code: Tensor, out: Tensor = None) -> Tensor:
Tim Dettmers's avatar
Tim Dettmers committed
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
    '''
    Quantizes input tensor to 8-bit.

    Quantizes the 32-bit input tensor `A` to the 8-bit output tensor
    `out` using the quantization map `code`.

    Parameters
    ----------
    A : torch.Tensor
        The input tensor.
    code : torch.Tensor
        The quantization map.
    out : torch.Tensor, optional
        The output tensor. Needs to be of type byte.

    Returns
    -------
    torch.Tensor:
        Quantized 8-bit tensor.
    '''
1041
    prev_device = pre_call(A.device)
Tim Dettmers's avatar
Tim Dettmers committed
1042
    if out is None: out = torch.zeros_like(A, dtype=torch.uint8)
1043
    is_on_gpu([A, out])
Tim Dettmers's avatar
Tim Dettmers committed
1044
    lib.cquantize(get_ptr(code), get_ptr(A), get_ptr(out), ct.c_int(A.numel()))
1045
    post_call(prev_device)
Tim Dettmers's avatar
Tim Dettmers committed
1046
1047
    return out

1048
1049

def dequantize_no_absmax(A: Tensor, code: Tensor, out: Tensor = None) -> Tensor:
Tim Dettmers's avatar
Tim Dettmers committed
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
    '''
    Dequantizes the 8-bit tensor to 32-bit.

    Dequantizes the 8-bit tensor `A` to the 32-bit tensor `out` via
    the quantization map `code`.

    Parameters
    ----------
    A : torch.Tensor
        The 8-bit input tensor.
    code : torch.Tensor
        The quantization map.
    out : torch.Tensor
        The 32-bit output tensor.

    Returns
    -------
    torch.Tensor:
        32-bit output tensor.
    '''
1070
    prev_device = pre_call(A.device)
Tim Dettmers's avatar
Tim Dettmers committed
1071
    if out is None: out = torch.zeros_like(A, dtype=torch.float32)
1072
    is_on_gpu([code, A, out])
Tim Dettmers's avatar
Tim Dettmers committed
1073
    lib.cdequantize(get_ptr(code), get_ptr(A), get_ptr(out), ct.c_int(A.numel()))
1074
    post_call(prev_device)
Tim Dettmers's avatar
Tim Dettmers committed
1075
1076
    return out

1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095

def optimizer_update_32bit(
    optimizer_name: str,
    g: Tensor,
    p: Tensor,
    state1: Tensor,
    beta1: float,
    eps: float,
    step: int,
    lr: float,
    state2: Tensor = None,
    beta2: float = 0.0,
    weight_decay: float = 0.0,
    gnorm_scale: float = 1.0,
    unorm_vec: Tensor = None,
    max_unorm: float = 0.0,
    skip_zeros=False,
) -> None:
    """
Tim Dettmers's avatar
Tim Dettmers committed
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
    Performs an inplace optimizer update with one or two optimizer states.

    Universal optimizer update for 32-bit state and 32/16-bit gradients/weights.

    Parameters
    ----------
    optimizer_name : str
        The name of the optimizer: {adam}.
    g : torch.Tensor
        Gradient tensor.
    p : torch.Tensor
        Parameter tensor.
    state1 : torch.Tensor
        Optimizer state 1.
    beta1 : float
        Optimizer beta1.
    eps : float
        Optimizer epsilon.
    weight_decay : float
        Weight decay.
    step : int
        Current optimizer step.
    lr : float
        The learning rate.
    state2 : torch.Tensor
        Optimizer state 2.
    beta2 : float
        Optimizer beta2.
    gnorm_scale : float
        The factor to rescale the gradient to the max clip value.
1126
1127
1128
1129
1130
1131
    unorm_vec : torch.Tensor
        The tensor for the update norm.
    max_unorm : float
        The maximum update norm relative to the weight norm.
    skip_zeros : bool
        Whether to skip zero-valued gradients or not (default: False).
1132
    """
Tim Dettmers's avatar
Tim Dettmers committed
1133
1134
1135
1136
1137
1138

    param_norm = 0.0
    if max_unorm > 0.0:
        param_norm = torch.norm(p.data.float())


1139
1140
1141
1142
1143
1144
1145
    optim_func = None
    if g.dtype == torch.float32:
        optim_func = str2optimizer32bit[optimizer_name][0]
    elif g.dtype == torch.float16:
        optim_func = str2optimizer32bit[optimizer_name][1]
    elif (g.dtype == torch.bfloat16 and len(str2optimizer32bit[optimizer_name])==3):
        optim_func = str2optimizer32bit[optimizer_name][2]
Tim Dettmers's avatar
Tim Dettmers committed
1146
    else:
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
        raise ValueError(f"Gradient+optimizer bit data type combination not supported: grad {g.dtype}, optimizer {state1.dtype}")

    is_on_gpu([g, p, state1, state2, unorm_vec])
    prev_device = pre_call(g.device)
    optim_func(
        get_ptr(g),
        get_ptr(p),
        get_ptr(state1),
        get_ptr(state2),
        get_ptr(unorm_vec),
        ct.c_float(max_unorm),
        ct.c_float(param_norm),
        ct.c_float(beta1),
        ct.c_float(beta2),
        ct.c_float(eps),
        ct.c_float(weight_decay),
        ct.c_int32(step),
        ct.c_float(lr),
        ct.c_float(gnorm_scale),
        ct.c_bool(skip_zeros),
        ct.c_int32(g.numel()))
    post_call(prev_device)
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193


def optimizer_update_8bit(
    optimizer_name: str,
    g: Tensor,
    p: Tensor,
    state1: Tensor,
    state2: Tensor,
    beta1: float,
    beta2: float,
    eps: float,
    step: int,
    lr: float,
    qmap1: Tensor,
    qmap2: Tensor,
    max1: Tensor,
    max2: Tensor,
    new_max1: Tensor,
    new_max2: Tensor,
    weight_decay: float = 0.0,
    gnorm_scale: float = 1.0,
    unorm_vec: Tensor = None,
    max_unorm: float = 0.0,
) -> None:
    """
Tim Dettmers's avatar
Tim Dettmers committed
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
    Performs an inplace Adam update.

    Universal Adam update for 32/8-bit state and 32/16-bit gradients/weights.
    Uses AdamW formulation if weight decay > 0.0.

    Parameters
    ----------
    optimizer_name : str
        The name of the optimizer. Choices {adam, momentum}
    g : torch.Tensor
        Gradient tensor.
    p : torch.Tensor
        Parameter tensor.
    state1 : torch.Tensor
        Adam state 1.
    state2 : torch.Tensor
        Adam state 2.
    beta1 : float
        Adam beta1.
    beta2 : float
        Adam beta2.
    eps : float
        Adam epsilon.
    weight_decay : float
        Weight decay.
    step : int
        Current optimizer step.
    lr : float
        The learning rate.
    qmap1 : torch.Tensor
        Quantization map for first Adam state.
    qmap2 : torch.Tensor
        Quantization map for second Adam state.
    max1 : torch.Tensor
        Max value for first Adam state update.
    max2 : torch.Tensor
        Max value for second Adam state update.
    new_max1 : torch.Tensor
        Max value for the next Adam update of the first state.
    new_max2 : torch.Tensor
        Max value for the next Adam update of the second state.
    gnorm_scale : float
        The factor to rescale the gradient to the max clip value.
1237
1238
1239
1240
    unorm_vec : torch.Tensor
        The tensor for the update norm.
    max_unorm : float
        The maximum update norm relative to the weight norm.
1241
    """
Tim Dettmers's avatar
Tim Dettmers committed
1242
1243
1244
1245
1246

    param_norm = 0.0
    if max_unorm > 0.0:
        param_norm = torch.norm(p.data.float())

1247
1248
    prev_device = pre_call(g.device)
    is_on_gpu([g, p, state1, state2, unorm_vec, qmap1, qmap2, max1, max2, new_max1, new_max2])
Tim Dettmers's avatar
Tim Dettmers committed
1249
    if g.dtype == torch.float32 and state1.dtype == torch.uint8:
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
        str2optimizer8bit[optimizer_name][0](
            get_ptr(p),
            get_ptr(g),
            get_ptr(state1),
            get_ptr(state2),
            get_ptr(unorm_vec),
            ct.c_float(max_unorm),
            ct.c_float(param_norm),
            ct.c_float(beta1),
            ct.c_float(beta2),
            ct.c_float(eps),
            ct.c_int32(step),
            ct.c_float(lr),
            get_ptr(qmap1),
            get_ptr(qmap2),
            get_ptr(max1),
            get_ptr(max2),
            get_ptr(new_max1),
            get_ptr(new_max2),
            ct.c_float(weight_decay),
            ct.c_float(gnorm_scale),
            ct.c_int32(g.numel()),
        )
Tim Dettmers's avatar
Tim Dettmers committed
1273
    elif g.dtype == torch.float16 and state1.dtype == torch.uint8:
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
        str2optimizer8bit[optimizer_name][1](
            get_ptr(p),
            get_ptr(g),
            get_ptr(state1),
            get_ptr(state2),
            get_ptr(unorm_vec),
            ct.c_float(max_unorm),
            ct.c_float(param_norm),
            ct.c_float(beta1),
            ct.c_float(beta2),
            ct.c_float(eps),
            ct.c_int32(step),
            ct.c_float(lr),
            get_ptr(qmap1),
            get_ptr(qmap2),
            get_ptr(max1),
            get_ptr(max2),
            get_ptr(new_max1),
            get_ptr(new_max2),
            ct.c_float(weight_decay),
            ct.c_float(gnorm_scale),
            ct.c_int32(g.numel()),
        )
Tim Dettmers's avatar
Tim Dettmers committed
1297
    else:
1298
1299
1300
        raise ValueError(
            f"Gradient+optimizer bit data type combination not supported: grad {g.dtype}, optimizer {state1.dtype}"
        )
1301
    post_call(prev_device)
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322


def optimizer_update_8bit_blockwise(
    optimizer_name: str,
    g: Tensor,
    p: Tensor,
    state1: Tensor,
    state2: Tensor,
    beta1: float,
    beta2: float,
    eps: float,
    step: int,
    lr: float,
    qmap1: Tensor,
    qmap2: Tensor,
    absmax1: Tensor,
    absmax2: Tensor,
    weight_decay: float = 0.0,
    gnorm_scale: float = 1.0,
    skip_zeros=False,
) -> None:
Tim Dettmers's avatar
Tim Dettmers committed
1323

Tim Dettmers's avatar
Tim Dettmers committed
1324
    optim_func = None
1325
1326
    prev_device = pre_call(g.device)
    is_on_gpu([g, p, state1, state2, qmap1, qmap2, absmax1, absmax2])
Tim Dettmers's avatar
Tim Dettmers committed
1327
    if g.dtype == torch.float32 and state1.dtype == torch.uint8:
1328
        optim_func = str2optimizer8bit_blockwise[optimizer_name][0]
Tim Dettmers's avatar
Tim Dettmers committed
1329
    elif g.dtype == torch.float16 and state1.dtype == torch.uint8:
1330
        optim_func = str2optimizer8bit_blockwise[optimizer_name][1]
Tim Dettmers's avatar
Tim Dettmers committed
1331
1332
    elif (g.dtype == torch.bfloat16 and state1.dtype == torch.uint8 and
          len(str2optimizer8bit_blockwise[optimizer_name])==3):
1333
        optim_func = str2optimizer8bit_blockwise[optimizer_name][2]
Tim Dettmers's avatar
Tim Dettmers committed
1334
    else:
1335
1336
1337
        raise ValueError(
            f"Gradient+optimizer bit data type combination not supported: grad {g.dtype}, optimizer {state1.dtype}"
        )
1338
    post_call(prev_device)
Tim Dettmers's avatar
Tim Dettmers committed
1339

Tim Dettmers's avatar
Tim Dettmers committed
1340
1341
1342
    is_on_gpu([p, g, state1, state2, qmap1, qmap2, absmax1, absmax2])

    prev_device = pre_call(g.device)
1343
    optim_func(
Tim Dettmers's avatar
Tim Dettmers committed
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
        get_ptr(p),
        get_ptr(g),
        get_ptr(state1),
        get_ptr(state2),
        ct.c_float(beta1),
        ct.c_float(beta2),
        ct.c_float(eps),
        ct.c_int32(step),
        ct.c_float(lr),
        get_ptr(qmap1),
        get_ptr(qmap2),
        get_ptr(absmax1),
        get_ptr(absmax2),
        ct.c_float(weight_decay),
        ct.c_float(gnorm_scale),
        ct.c_bool(skip_zeros),
        ct.c_int32(g.numel()),
    )
    post_call(prev_device)
Tim Dettmers's avatar
Tim Dettmers committed
1363

1364
1365
1366
def percentile_clipping(
    grad: Tensor, gnorm_vec: Tensor, step: int, percentile: int = 5
):
Tim Dettmers's avatar
Tim Dettmers committed
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
    """Applies percentile clipping

    grad: torch.Tensor
        The gradient tensor.
    gnorm_vec: torch.Tensor
        Vector of gradient norms. 100 elements expected.
    step: int
        The current optimiation steps (number of past gradient norms).

    """
1377
    prev_device = pre_call(grad.device)
1378
    is_on_gpu([grad, gnorm_vec])
Tim Dettmers's avatar
Tim Dettmers committed
1379
    if grad.dtype == torch.float32:
1380
1381
1382
1383
1384
1385
        lib.cpercentile_clipping_g32(
            get_ptr(grad),
            get_ptr(gnorm_vec),
            ct.c_int32(step),
            ct.c_int32(grad.numel()),
        )
Tim Dettmers's avatar
Tim Dettmers committed
1386
    elif grad.dtype == torch.float16:
1387
1388
1389
1390
1391
1392
        lib.cpercentile_clipping_g16(
            get_ptr(grad),
            get_ptr(gnorm_vec),
            ct.c_int32(step),
            ct.c_int32(grad.numel()),
        )
Tim Dettmers's avatar
Tim Dettmers committed
1393
    else:
1394
        raise ValueError(f"Gradient type {grad.dtype} not supported!")
1395
    post_call(prev_device)
Tim Dettmers's avatar
Tim Dettmers committed
1396
1397
1398
1399
1400
1401
1402

    current_gnorm = torch.sqrt(gnorm_vec[step % 100])
    vals, idx = torch.sort(gnorm_vec)
    clip_value = torch.sqrt(vals[percentile])
    gnorm_scale = 1.0

    if current_gnorm > clip_value:
1403
        gnorm_scale = clip_value / current_gnorm
Tim Dettmers's avatar
Tim Dettmers committed
1404
1405
1406
1407

    return current_gnorm, clip_value, gnorm_scale


1408
1409
1410
def histogram_scatter_add_2d(
    histogram: Tensor, index1: Tensor, index2: Tensor, source: Tensor
):
Tim Dettmers's avatar
Tim Dettmers committed
1411
1412
1413
1414
1415
1416
    assert len(histogram.shape) == 2
    assert histogram.dtype == torch.float32
    assert source.dtype == torch.float32
    assert index1.dtype == torch.int32
    assert index2.dtype == torch.int32

1417
1418
1419
1420
    assert histogram.device.type == "cuda"
    assert index1.device.type == "cuda"
    assert index2.device.type == "cuda"
    assert source.device.type == "cuda"
Tim Dettmers's avatar
Tim Dettmers committed
1421
1422
1423

    maxdim1 = ct.c_int32(histogram.shape[0])
    n = ct.c_int32(index1.numel())
1424
    is_on_gpu([histogram, index1, index2, source])
Tim Dettmers's avatar
Tim Dettmers committed
1425
    lib.chistogram_scatter_add_2d(get_ptr(histogram), get_ptr(index1), get_ptr(index2), get_ptr(source), maxdim1, n)
1426

Tim Dettmers's avatar
Tim Dettmers committed
1427
1428
1429
def check_matmul(A, B, out, transposed_A, transposed_B, expected_type=torch.int8):
    if not torch.cuda.is_initialized(): torch.cuda.init()
    if A.dtype != expected_type or B.dtype != expected_type:
1430
1431
1432
        raise TypeError(
            f"Expected torch.int8 input tensors A and B, but got {A.dtype} and {B.dtype}"
        )
Tim Dettmers's avatar
Tim Dettmers committed
1433
1434
1435
1436
1437
1438
1439
1440
1441

    sA = A.shape
    sB = B.shape
    tA = transposed_A
    tB = transposed_B

    correct = True

    if len(sA) == 2 and len(sB) == 2:
1442
1443
1444
1445
1446
1447
1448
1449
        if not tA and not tB and A.shape[1] != B.shape[0]:
            correct = False
        elif tA and not tB and A.shape[0] != B.shape[0]:
            correct = False
        elif tA and tB and A.shape[0] != B.shape[1]:
            correct = False
        elif not tA and tB and A.shape[1] != B.shape[1]:
            correct = False
Tim Dettmers's avatar
Tim Dettmers committed
1450
    elif len(sA) == 3 and len(sB) == 2:
1451
1452
1453
1454
1455
1456
1457
1458
        if not tA and not tB and A.shape[2] != B.shape[0]:
            correct = False
        elif tA and not tB and A.shape[1] != B.shape[0]:
            correct = False
        elif tA and tB and A.shape[1] != B.shape[1]:
            correct = False
        elif not tA and tB and A.shape[2] != B.shape[1]:
            correct = False
Tim Dettmers's avatar
Tim Dettmers committed
1459
    elif len(sA) == 3 and len(sB) == 3:
1460
1461
1462
1463
1464
1465
1466
1467
        if not tA and not tB and A.shape[2] != B.shape[1]:
            correct = False
        elif tA and not tB and A.shape[1] != B.shape[1]:
            correct = False
        elif tA and tB and A.shape[1] != B.shape[2]:
            correct = False
        elif not tA and tB and A.shape[2] != B.shape[2]:
            correct = False
Tim Dettmers's avatar
Tim Dettmers committed
1468
1469
1470
1471
1472

    if out is not None:
        sout = out.shape
        # special case common in backprop
        if not correct and len(sA) == 3 and len(sB) == 3:
1473
1474
1475
1476
1477
1478
            if (
                sout[0] == sA[2]
                and sout[1] == sB[2]
                and sA[0] == sB[0]
                and sA[1] == sB[1]
            ):
Tim Dettmers's avatar
Tim Dettmers committed
1479
1480
1481
                correct = True
    else:
        if len(sA) == 2 and len(sB) == 2:
1482
1483
1484
1485
1486
1487
1488
1489
            if not tA and not tB:
                sout = (sA[0], sB[1])
            elif tA and tB:
                sout = (sA[1], sB[0])
            elif tA and not tB:
                sout = (sA[1], sB[1])
            elif not tA and tB:
                sout = (sA[0], sB[0])
Tim Dettmers's avatar
Tim Dettmers committed
1490
        elif len(sA) == 3 and len(sB) == 2:
1491
1492
1493
1494
1495
1496
1497
1498
            if not tA and not tB:
                sout = (sA[0], sA[1], sB[1])
            elif tA and tB:
                sout = (sA[0], sA[2], sB[0])
            elif tA and not tB:
                sout = (sA[0], sA[2], sB[1])
            elif not tA and tB:
                sout = (sA[0], sA[1], sB[0])
Tim Dettmers's avatar
Tim Dettmers committed
1499
        elif len(sA) == 3 and len(sB) == 3:
1500
1501
1502
1503
1504
1505
1506
1507
            if not tA and not tB:
                sout = (sA[0], sA[1], sB[2])
            elif tA and tB:
                sout = (sA[0], sA[2], sB[1])
            elif tA and not tB:
                sout = (sA[0], sA[2], sB[2])
            elif not tA and tB:
                sout = (sA[0], sA[1], sB[1])
Tim Dettmers's avatar
Tim Dettmers committed
1508
1509

    if not correct:
1510
1511
1512
        raise ValueError(
            f"Tensor dimensions incorrect for matrix mulitiplication: A x B: {sA} x {sB} with transpose for A x B: {tA} x {tB}."
        )
Tim Dettmers's avatar
Tim Dettmers committed
1513
1514
1515

    return sout

1516
def gemv_4bit(
Tim Dettmers's avatar
Tim Dettmers committed
1517
1518
1519
1520
1521
    A: Tensor,
    B: Tensor,
    out: Tensor = None,
    transposed_A=False,
    transposed_B=False,
1522
    quant_state=None
Tim Dettmers's avatar
Tim Dettmers committed
1523
):
1524
    prev_device = pre_call(A.device)
Tim Dettmers's avatar
Tim Dettmers committed
1525
    #sout = check_matmul(A, B, out, transposed_A, transposed_B, expected_type=A.dtype)
1526
    if quant_state is None:
1527
1528
        raise ValueError(f'state cannot None. gem_4bit( ) requires the state from quantize_4bit( )')

1529
1530
1531
    if A.numel() != A.shape[-1]:
        raise ValueError(f'Dimensions of A are invalid. Must be a vector with the leading dimensions of "1", e.g. [1, 1, 2048]')

1532
    Bshape = quant_state.shape
1533
    bout = Bshape[0]
1534
1535
1536
1537
    absmax = quant_state.absmax
    if quant_state.nested:
        absmax = dequantize_blockwise(quant_state.absmax, quant_state.state2)
        absmax += quant_state.offset
1538

Tim Dettmers's avatar
Tim Dettmers committed
1539
    if out is None:
1540
        if len(A.shape) == 3:
1541
            out = torch.empty(size=(A.shape[0], A.shape[1], bout), dtype=A.dtype, device=A.device)
1542
        else:
1543
1544
1545
1546
1547
1548
1549
1550
            out = torch.empty(size=(A.shape[0], bout), dtype=A.dtype, device=A.device)

    n = 1
    m = Bshape[0]
    k = Bshape[1]
    lda = Bshape[0]
    ldc = Bshape[0]
    ldb = (A.shape[-1]+1)//2
1551
    is_on_gpu([B, A, out, absmax, quant_state.code])
Tim Dettmers's avatar
Tim Dettmers committed
1552
1553
1554
1555
1556
1557
    m = ct.c_int32(m)
    n = ct.c_int32(n)
    k = ct.c_int32(k)
    lda = ct.c_int32(lda)
    ldb = ct.c_int32(ldb)
    ldc = ct.c_int32(ldc)
Tim Dettmers's avatar
Tim Dettmers committed
1558
1559

    if B.dtype == torch.uint8:
1560
        if A.dtype == torch.float16:
1561
            lib.cgemm_4bit_inference_naive_fp16(m, n, k, get_ptr(A), get_ptr(B), get_ptr(absmax), get_ptr(quant_state.code), get_ptr(out), lda, ldb, ldc, ct.c_int32(quant_state.blocksize))
1562
        elif A.dtype == torch.bfloat16:
1563
            lib.cgemm_4bit_inference_naive_bf16(m, n, k, get_ptr(A), get_ptr(B), get_ptr(absmax), get_ptr(quant_state.code), get_ptr(out), lda, ldb, ldc, ct.c_int32(quant_state.blocksize))
1564
        elif A.dtype == torch.float32:
1565
            lib.cgemm_4bit_inference_naive_fp32(m, n, k, get_ptr(A), get_ptr(B), get_ptr(absmax), get_ptr(quant_state.code), get_ptr(out), lda, ldb, ldc, ct.c_int32(quant_state.blocksize))
1566
1567
        else:
            raise NotImplementedError(f'Matmul not implemented for data type {A.dtype}')
1568

1569
1570
    else:
        raise NotImplementedError(f'Matmul not implemented for data type {A.dtype}')
Tim Dettmers's avatar
Tim Dettmers committed
1571

1572
1573
    post_call(prev_device)

Tim Dettmers's avatar
Tim Dettmers committed
1574
1575
    return out

1576
def igemm(
1577
1578
1579
1580
1581
    A: Tensor,
    B: Tensor,
    out: Tensor = None,
    transposed_A=False,
    transposed_B=False,
1582
):
Tim Dettmers's avatar
Tim Dettmers committed
1583
    sout = check_matmul(A, B, out, transposed_A, transposed_B)
1584
1585
    if out is None:
        out = torch.zeros(size=sout, dtype=torch.int32, device=A.device)
Tim Dettmers's avatar
Tim Dettmers committed
1586
1587
1588
1589
1590
1591
    if len(A.shape) == 3 and len(B.shape) == 3:
        if A.shape[0] == B.shape[0] and A.shape[2] == B.shape[1]:
            return batched_igemm(A, B, out)

    sA = A.shape
    sB = B.shape
1592
1593
1594
1595
1596
1597
1598
1599
    if transposed_A and len(sA) == 2:
        sA = (sA[1], sA[0])
    elif transposed_A and len(sA) == 3:
        sA = (sA[0], sA[2], sA[0])
    if transposed_B and len(sB) == 2:
        sB = (sB[1], sB[0])
    elif transposed_B and len(sB) == 3:
        sB = (sB[0], sB[2], sB[0])
Tim Dettmers's avatar
Tim Dettmers committed
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
    # this is a mess: cuBLAS expect column major, but PyTorch is row major.
    # So to perform the matrix multiplication, we have to treat A, B, and C matrices
    # (transpose of row major is column major)
    # This means we compute B^T A^T = C^T and we explicitly switch the dimensions of each of these

    # matrices in the input arguments for cuBLAS
    # column major: A @ B = C: [m, k] @ [k, n] = [m, n]
    # row major: B^T @ A^T = C^T: [m, k] @ [k, n] = [m, n]
    # column major with row major layout: B^T @ A^T = C^T: [k, m] @ [n, k] = [n, m]
    if len(sB) == 2:
1610
1611
1612
1613
        if B.stride()[0] == B.shape[1]:
            transposed_B = False
        elif B.stride()[1] == B.shape[0]:
            transposed_B = True
Tim Dettmers's avatar
Tim Dettmers committed
1614
        if len(A.shape) == 2:
1615
1616
1617
1618
            if A.stride()[0] == A.shape[1]:
                transposed_A = False
            elif A.stride()[1] == A.shape[0]:
                transposed_A = True
Tim Dettmers's avatar
Tim Dettmers committed
1619
        else:
1620
1621
1622
1623
            if A.stride()[1] == A.shape[2]:
                transposed_A = False
            elif A.stride()[2] == A.shape[1]:
                transposed_A = True
Tim Dettmers's avatar
Tim Dettmers committed
1624
1625
1626
1627
1628

        if len(sA) == 2:
            n = sA[0]
            ldb = A.stride()[1 if transposed_A else 0]
        elif len(sA) == 3 and len(sB) == 2:
1629
            n = sA[0] * sA[1]
Tim Dettmers's avatar
Tim Dettmers committed
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
            ldb = sA[2]

        m = sB[1]
        k = sB[0]
        lda = B.stride()[(1 if transposed_B else 0)]
        ldc = sB[1]
    elif len(sB) == 3:
        # special case
        assert len(sA) == 3
        if not (sA[0] == sB[0] and sA[1] == sB[1]):
1640
1641
1642
            raise ValueError(
                f"Only bsi,bso->io supported for tensor contractions, but dims for A x B were: {sA} x {sB}"
            )
Tim Dettmers's avatar
Tim Dettmers committed
1643
1644
1645
1646
1647
1648

        transposed_A = True
        transposed_B = False

        m = sB[2]
        n = sA[2]
1649
        k = sB[0] * sB[1]
Tim Dettmers's avatar
Tim Dettmers committed
1650
1651
1652
1653
1654
1655
1656
1657

        lda = m
        ldb = sA[2]
        ldc = m

    ptr = CUBLAS_Context.get_instance().get_context(A.device)

    # B^T @ A^T = C^T
1658
    # [km, nk -> mn]
1659
    is_on_gpu([B, A, out])
Tim Dettmers's avatar
Tim Dettmers committed
1660
1661
1662
1663
1664
    lib.cigemm(ptr, ct.c_bool(transposed_B), ct.c_bool(transposed_A), ct.c_int32(m), ct.c_int32(n), ct.c_int32(k),
               get_ptr(B), get_ptr(A), get_ptr(out), ct.c_int32(lda), ct.c_int32(ldb), ct.c_int32(ldc))
    return out


1665
def batched_igemm(
1666
1667
1668
1669
1670
    A: Tensor,
    B: Tensor,
    out: Tensor = None,
    transposed_A=False,
    transposed_B=False,
1671
):
Tim Dettmers's avatar
Tim Dettmers committed
1672
    if not len(A.shape) == 3 or not len(B.shape) == 3:
1673
1674
1675
        raise ValueError(
            f"Expected 3-dimensional tensors for bmm, but got shapes A and B: {A.shape} and {B.shape}"
        )
Tim Dettmers's avatar
Tim Dettmers committed
1676
    sout = check_matmul(A, B, out, transposed_A, transposed_B)
1677
1678
    if out is None:
        out = torch.zeros(size=sout, dtype=torch.int32, device=A.device)
Tim Dettmers's avatar
Tim Dettmers committed
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734

    if B.is_contiguous():
        lda = B.stride()[1]
        transposed_A = False
    else:
        s = B.stride()
        if s[0] != B.shape[0]:
            B = B.contiguous()
            lda = B.stride()[1]
        elif s[2] == B.shape[1]:
            transposed_A = True
            lda = B.stride()[2]
        else:
            if s[2] == 1:
                B = B.contiguous()
                lda = B.stride()[1]
            elif s[1] == 1:
                B = B.contiguous()
                lda = B.stride()[1]
            else:
                B = B.contiguous()
                lda = B.stride()[1]

    if A.is_contiguous():
        ldb = A.stride()[1]
        transposed_B = False
    else:
        s = A.stride()
        if s[0] != A.shape[0]:
            A = A.contiguous()
            ldb = A.stride()[1]
            transposed_B = False
        elif s[2] == A.shape[1]:
            ldb = A.stride()[2]
            transposed_B = True
        else:
            A = A.contiguous()
            ldb = A.stride()[1]
            transposed_B = False

    # this is a mess: cuBLAS expect column major, but PyTorch is row major.
    # So to perform the matrix multiplication, we have to treat A, B, and C matrices
    # (transpose of row major is column major)
    # This means we compute B^T A^T = C^T and we explicitly switch the dimensions of each of these
    # matrices in the input arguments for cuBLAS

    # column major: A @ B = C: [batch, m, k] @ [batch, k, n] = [batch, m, n]
    # row major: B^T @ A^T = C^T: [batch, m, k] @ [batch, k, n] = [batch, m, n]
    # column major with row major layout: B^T @ A^T = C^T: [batch, k, m] @ [batch, n, k] = [batch, n, m]
    num_batch = A.shape[0]
    n = A.shape[1]
    m = B.shape[2]
    k = B.shape[1]

    ldc = m

1735
1736
1737
    strideA = B.shape[1] * B.shape[2]
    strideB = A.shape[1] * A.shape[2]
    strideC = A.shape[1] * B.shape[2]
Tim Dettmers's avatar
Tim Dettmers committed
1738
1739
1740

    ptr = CUBLAS_Context.get_instance().get_context(A.device)

1741
    is_on_gpu([B, A, out])
Tim Dettmers's avatar
Tim Dettmers committed
1742
1743
1744
1745
1746
    lib.cbatched_igemm(ptr, ct.c_bool(transposed_B), ct.c_bool(transposed_A), ct.c_int32(m), ct.c_int32(n), ct.c_int32(k),
               get_ptr(B), get_ptr(A), get_ptr(out), ct.c_int32(lda), ct.c_int32(ldb), ct.c_int32(ldc),
               ct.c_long(strideA), ct.c_long(strideB), ct.c_long(strideC), ct.c_uint32(num_batch))
    return out

1747

1748
def igemmlt(A, B, SA, SB, out=None, Sout=None, dtype=torch.int32):
Tim Dettmers's avatar
Tim Dettmers committed
1749
1750
1751
1752
    shapeA = SA[0]
    shapeB = SB[0]
    dimsA = len(shapeA)
    dimsB = len(shapeB)
1753
    assert dimsB == 2, 'Only two dimensional matrices are supported for argument B'
Tim Dettmers's avatar
Tim Dettmers committed
1754
1755
1756
    if dimsA == 2:
        m = shapeA[0]
    elif dimsA == 3:
1757
        m = shapeA[0] * shapeA[1]
Tim Dettmers's avatar
Tim Dettmers committed
1758

1759
    rows = n = shapeB[0]
1760
    assert prod(list(shapeA)) > 0, f'Input tensor dimensions need to be > 0: {shapeA}'
1761
1762
1763
1764
1765
1766

    # if the tensor is empty, return a transformed empty tensor with the right dimensions
    if shapeA[0] == 0 and dimsA == 2:
        return torch.empty((0, shapeB[0]), device=A.device, dtype=torch.float16)
    elif shapeA[1] == 0 and dimsA == 3:
        return torch.empty(tuple(shapeA[:2] + [shapeB[0]]), device=A.device, dtype=torch.float16)
Tim Dettmers's avatar
Tim Dettmers committed
1767
1768

    if dimsA == 2 and out is None:
1769
1770
1771
        out, Sout = get_transform_buffer(
            (shapeA[0], shapeB[0]), dtype, A.device, "col32", "row"
        )
Tim Dettmers's avatar
Tim Dettmers committed
1772
    elif dimsA == 3 and out is None:
1773
1774
1775
        out, Sout = get_transform_buffer(
            (shapeA[0], shapeA[1], shapeB[0]), dtype, A.device, "col32", "row"
        )
Tim Dettmers's avatar
Tim Dettmers committed
1776

1777
1778
1779
    assert dimsB != 3, "len(B.shape)==3 not supported"
    assert A.device.type == "cuda"
    assert B.device.type == "cuda"
Tim Dettmers's avatar
Tim Dettmers committed
1780
1781
1782
    assert A.dtype == torch.int8
    assert B.dtype == torch.int8
    assert out.dtype == dtype
1783
1784
1785
1786
1787
1788
    assert SA[1] == "col32"
    assert SB[1] in ["col_turing", "col_ampere"]
    assert Sout[1] == "col32"
    assert (
        shapeA[-1] == shapeB[-1]
    ), f"Matmullt only supports A @ B^T. Inner matrix dimensions do not match: A @ B = {shapeA} @ {shapeB}"
Tim Dettmers's avatar
Tim Dettmers committed
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
    formatB = SB[1]
    prev_device = A.device
    torch.cuda.set_device(A.device)

    ptr = CUBLAS_Context.get_instance().get_context(A.device)
    ptrA = get_ptr(A)
    ptrB = get_ptr(B)
    ptrC = get_ptr(out)

    k = shapeA[-1]
1799
1800
    lda = ct.c_int32(m * 32)
    if formatB == "col_turing":
Tim Dettmers's avatar
Tim Dettmers committed
1801
1802
        # turing: tiles with rows filled up to multiple of 8 rows by 32 columns
        # n = rows
1803
        ldb = ct.c_int32(((rows + 7) // 8) * 8 * 32)
Tim Dettmers's avatar
Tim Dettmers committed
1804
1805
1806
    else:
        # ampere: tiles with rows filled up to multiple of 32 rows by 32 columns
        # n = rows
1807
        ldb = ct.c_int32(((rows + 31) // 32) * 32 * 32)
Tim Dettmers's avatar
Tim Dettmers committed
1808

1809
    ldc = ct.c_int32(m * 32)
Tim Dettmers's avatar
Tim Dettmers committed
1810
1811
1812
1813
1814
    m = ct.c_int32(m)
    n = ct.c_int32(n)
    k = ct.c_int32(k)

    has_error = 0
1815
    ptrRowScale = get_ptr(None)
1816
    is_on_gpu([A, B, out])
Tim Dettmers's avatar
Tim Dettmers committed
1817
1818
    if formatB == 'col_turing':
        if dtype == torch.int32:
1819
1820
1821
            has_error = lib.cigemmlt_turing_32(
                ptr, m, n, k, ptrA, ptrB, ptrC, ptrRowScale, lda, ldb, ldc
            )
Tim Dettmers's avatar
Tim Dettmers committed
1822
        else:
1823
1824
1825
1826
            has_error = lib.cigemmlt_turing_8(
                ptr, m, n, k, ptrA, ptrB, ptrC, ptrRowScale, lda, ldb, ldc
            )
    elif formatB == "col_ampere":
Tim Dettmers's avatar
Tim Dettmers committed
1827
        if dtype == torch.int32:
1828
1829
1830
            has_error = lib.cigemmlt_ampere_32(
                ptr, m, n, k, ptrA, ptrB, ptrC, ptrRowScale, lda, ldb, ldc
            )
Tim Dettmers's avatar
Tim Dettmers committed
1831
        else:
1832
1833
1834
            has_error = lib.cigemmlt_ampere_8(
                ptr, m, n, k, ptrA, ptrB, ptrC, ptrRowScale, lda, ldb, ldc
            )
Tim Dettmers's avatar
Tim Dettmers committed
1835
1836

    if has_error == 1:
1837
        print(f'A: {shapeA}, B: {shapeB}, C: {Sout[0]}; (lda, ldb, ldc): {(lda, ldb, ldc)}; (m, n, k): {(m, n, k)}')
Tim Dettmers's avatar
Tim Dettmers committed
1838
1839
1840
1841
1842
1843
1844
        raise Exception('cublasLt ran into an error!')

    torch.cuda.set_device(prev_device)

    return out, Sout


1845
1846
def mm_dequant(
    A,
1847
    state,
1848
1849
1850
1851
1852
    row_stats,
    col_stats,
    out=None,
    new_row_stats=None,
    new_col_stats=None,
1853
    bias=None
1854
):
Tim Dettmers's avatar
Tim Dettmers committed
1855
    assert A.dtype == torch.int32
1856
    if bias is not None: assert bias.dtype == torch.float16
1857
    out_shape = state[0]
1858
1859
1860
1861
1862
1863
    if len(out_shape) == 3:
        out_shape = (out_shape[0] * out_shape[1], out_shape[2])

    if out is None:
        out = torch.empty(out_shape, dtype=torch.float16, device=A.device)
    if new_row_stats is None:
1864
1865
1866
        new_row_stats = torch.empty(
            out_shape[0], dtype=torch.float32, device=A.device
        )
1867
    if new_col_stats is None:
1868
1869
1870
        new_col_stats = torch.empty(
            out_shape[1], dtype=torch.float32, device=A.device
        )
1871
1872
1873
1874
1875
1876
    assert (
        new_row_stats.shape[0] == row_stats.shape[0]
    ), f"{new_row_stats.shape} vs {row_stats.shape}"
    assert (
        new_col_stats.shape[0] == col_stats.shape[0]
    ), f"{new_col_stats.shape} vs {col_stats.shape}"
Tim Dettmers's avatar
Tim Dettmers committed
1877

1878
    prev_device = pre_call(A.device)
Tim Dettmers's avatar
Tim Dettmers committed
1879
1880
1881
1882
1883
1884
    ptrA = get_ptr(A)
    ptrOut = get_ptr(out)
    ptrRowStats = get_ptr(row_stats)
    ptrColStats = get_ptr(col_stats)
    ptrNewRowStats = get_ptr(new_row_stats)
    ptrNewColStats = get_ptr(new_col_stats)
1885
    ptrBias = get_ptr(bias)
Tim Dettmers's avatar
Tim Dettmers committed
1886
1887
1888
    numRows = ct.c_int32(out_shape[0])
    numCols = ct.c_int32(out_shape[1])

1889
1890
1891
    is_on_gpu([A, row_stats, col_stats, out, new_row_stats, new_col_stats, bias])
    lib.cdequant_mm_int32_fp16(ptrA, ptrRowStats, ptrColStats, ptrOut, ptrNewRowStats, ptrNewColStats, ptrBias, numRows, numCols)
    post_call(prev_device)
Tim Dettmers's avatar
Tim Dettmers committed
1892
1893
1894
1895

    return out


1896
1897
1898
def get_colrow_absmax(
    A, row_stats=None, col_stats=None, nnz_block_ptr=None, threshold=0.0
):
Tim Dettmers's avatar
Tim Dettmers committed
1899
1900
1901
1902
1903
    assert A.dtype == torch.float16
    device = A.device

    cols = A.shape[-1]
    if len(A.shape) == 3:
1904
        rows = A.shape[0] * A.shape[1]
Tim Dettmers's avatar
Tim Dettmers committed
1905
1906
1907
    else:
        rows = A.shape[0]

1908
1909
1910
    col_tiles = (cols + 255) // 256
    tiled_rows = ((rows + 15) // 16) * 16
    if row_stats is None:
1911
1912
1913
        row_stats = torch.empty(
            (rows,), dtype=torch.float32, device=device
        ).fill_(-50000.0)
1914
    if col_stats is None:
1915
1916
1917
        col_stats = torch.empty(
            (cols,), dtype=torch.float32, device=device
        ).fill_(-50000.0)
1918
1919
1920
1921
1922

    if nnz_block_ptr is None and threshold > 0.0:
        nnz_block_ptr = torch.zeros(
            ((tiled_rows * col_tiles) + 1,), dtype=torch.int32, device=device
        )
Tim Dettmers's avatar
Tim Dettmers committed
1923
1924
1925
1926
1927
1928
1929
1930
1931

    ptrA = get_ptr(A)
    ptrRowStats = get_ptr(row_stats)
    ptrColStats = get_ptr(col_stats)
    ptrNnzrows = get_ptr(nnz_block_ptr)
    rows = ct.c_int32(rows)
    cols = ct.c_int32(cols)

    prev_device = pre_call(A.device)
1932
    is_on_gpu([A, row_stats, col_stats, nnz_block_ptr])
Tim Dettmers's avatar
Tim Dettmers committed
1933
1934
1935
1936
1937
1938
1939
1940
    lib.cget_col_row_stats(ptrA, ptrRowStats, ptrColStats, ptrNnzrows, ct.c_float(threshold), rows, cols)
    post_call(prev_device)

    if threshold > 0.0:
        nnz_block_ptr.cumsum_(0)

    return row_stats, col_stats, nnz_block_ptr

1941

1942
class COOSparseTensor:
Tim Dettmers's avatar
Tim Dettmers committed
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
    def __init__(self, rows, cols, nnz, rowidx, colidx, values):
        assert rowidx.dtype == torch.int32
        assert colidx.dtype == torch.int32
        assert values.dtype == torch.float16
        assert values.numel() == nnz
        assert rowidx.numel() == nnz
        assert colidx.numel() == nnz

        self.rows = rows
        self.cols = cols
        self.nnz = nnz
        self.rowidx = rowidx
        self.colidx = colidx
        self.values = values

1958

1959
class CSRSparseTensor:
Tim Dettmers's avatar
Tim Dettmers committed
1960
1961
1962
1963
1964
1965
    def __init__(self, rows, cols, nnz, rowptr, colidx, values):
        assert rowptr.dtype == torch.int32
        assert colidx.dtype == torch.int32
        assert values.dtype == torch.float16
        assert values.numel() == nnz
        assert colidx.numel() == nnz
1966
        assert rowptr.numel() == rows + 1
Tim Dettmers's avatar
Tim Dettmers committed
1967
1968
1969
1970
1971
1972
1973
1974

        self.rows = rows
        self.cols = cols
        self.nnz = nnz
        self.rowptr = rowptr
        self.colidx = colidx
        self.values = values

1975

1976
class CSCSparseTensor:
Tim Dettmers's avatar
Tim Dettmers committed
1977
1978
1979
1980
1981
1982
    def __init__(self, rows, cols, nnz, colptr, rowidx, values):
        assert colptr.dtype == torch.int32
        assert rowidx.dtype == torch.int32
        assert values.dtype == torch.float16
        assert values.numel() == nnz
        assert rowidx.numel() == nnz
1983
        assert colptr.numel() == cols + 1
Tim Dettmers's avatar
Tim Dettmers committed
1984
1985
1986
1987
1988
1989
1990
1991

        self.rows = rows
        self.cols = cols
        self.nnz = nnz
        self.colptr = colptr
        self.rowidx = rowidx
        self.values = values

1992

Tim Dettmers's avatar
Tim Dettmers committed
1993
1994
1995
def coo2csr(cooA):
    values, counts = torch.unique(cooA.rowidx, return_counts=True)
    values.add_(1)
1996
1997
1998
    rowptr = torch.zeros(
        (cooA.rows + 1,), dtype=torch.int32, device=cooA.rowidx.device
    )
Tim Dettmers's avatar
Tim Dettmers committed
1999
2000
    rowptr.scatter_(index=values.long(), src=counts.int(), dim=0)
    rowptr.cumsum_(0)
2001
2002
2003
2004
    return CSRSparseTensor(
        cooA.rows, cooA.cols, cooA.nnz, rowptr, cooA.colidx, cooA.values
    )

Tim Dettmers's avatar
Tim Dettmers committed
2005
2006
2007
2008
2009
2010
2011

def coo2csc(cooA):
    val, col2rowidx = torch.sort(cooA.colidx)
    rowidx = cooA.rowidx[col2rowidx]
    values = cooA.values[col2rowidx]
    colvalues, counts = torch.unique(val, return_counts=True)
    colvalues.add_(1)
2012
2013
2014
    colptr = torch.zeros(
        (cooA.cols + 1,), dtype=torch.int32, device=cooA.colidx.device
    )
Tim Dettmers's avatar
Tim Dettmers committed
2015
2016
    colptr.scatter_(index=colvalues.long(), src=counts.int(), dim=0)
    colptr.cumsum_(0)
2017
2018
2019
    return CSCSparseTensor(
        cooA.rows, cooA.cols, cooA.nnz, colptr, rowidx, values
    )
Tim Dettmers's avatar
Tim Dettmers committed
2020

2021

Tim Dettmers's avatar
Tim Dettmers committed
2022
2023
2024
2025
2026
2027
2028
def coo_zeros(rows, cols, nnz, device, dtype=torch.half):
    rowidx = torch.zeros((nnz,), dtype=torch.int32, device=device)
    colidx = torch.zeros((nnz,), dtype=torch.int32, device=device)
    values = torch.zeros((nnz,), dtype=dtype, device=device)
    return COOSparseTensor(rows, cols, nnz, rowidx, colidx, values)


2029
2030
2031
def double_quant(
    A, col_stats=None, row_stats=None, out_col=None, out_row=None, threshold=0.0
):
Tim Dettmers's avatar
Tim Dettmers committed
2032
2033
    device = A.device
    assert A.dtype == torch.half
2034
    assert device.type == "cuda"
Tim Dettmers's avatar
Tim Dettmers committed
2035
2036
2037
2038
    prev_device = pre_call(A.device)

    cols = A.shape[-1]
    if len(A.shape) == 3:
2039
        rows = A.shape[0] * A.shape[1]
Tim Dettmers's avatar
Tim Dettmers committed
2040
2041
2042
2043
    else:
        rows = A.shape[0]

    if row_stats is None or col_stats is None:
2044
2045
2046
        row_stats, col_stats, nnz_row_ptr = get_colrow_absmax(
            A, threshold=threshold
        )
Tim Dettmers's avatar
Tim Dettmers committed
2047

2048
2049
2050
2051
    if out_col is None:
        out_col = torch.zeros(A.shape, device=device, dtype=torch.int8)
    if out_row is None:
        out_row = torch.zeros(A.shape, device=device, dtype=torch.int8)
Tim Dettmers's avatar
Tim Dettmers committed
2052
2053
2054
2055
2056
2057
2058
2059

    coo_tensor = None
    ptrA = get_ptr(A)
    ptrColStats = get_ptr(col_stats)
    ptrRowStats = get_ptr(row_stats)
    ptrOutCol = get_ptr(out_col)
    ptrOutRow = get_ptr(out_row)

2060
    is_on_gpu([A, col_stats, row_stats, out_col, out_row])
Tim Dettmers's avatar
Tim Dettmers committed
2061
2062
2063
    if threshold > 0.0:
        nnz = nnz_row_ptr[-1].item()
        if nnz > 0:
2064
2065
2066
            coo_tensor = coo_zeros(
                A.shape[0], A.shape[1], nnz_row_ptr[-1].item(), device
            )
Tim Dettmers's avatar
Tim Dettmers committed
2067
2068
2069
2070
2071
            ptrRowIdx = get_ptr(coo_tensor.rowidx)
            ptrColIdx = get_ptr(coo_tensor.colidx)
            ptrVal = get_ptr(coo_tensor.values)
            ptrRowPtr = get_ptr(nnz_row_ptr)

2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
            lib.cdouble_rowcol_quant(
                ptrA,
                ptrRowStats,
                ptrColStats,
                ptrOutCol,
                ptrOutRow,
                ptrRowIdx,
                ptrColIdx,
                ptrVal,
                ptrRowPtr,
                ct.c_float(threshold),
                ct.c_int32(rows),
                ct.c_int32(cols),
            )
Tim Dettmers's avatar
Tim Dettmers committed
2086
2087
2088
2089
2090
            val, idx = torch.sort(coo_tensor.rowidx)
            coo_tensor.rowidx = val
            coo_tensor.colidx = coo_tensor.colidx[idx]
            coo_tensor.values = coo_tensor.values[idx]
        else:
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
            lib.cdouble_rowcol_quant(
                ptrA,
                ptrRowStats,
                ptrColStats,
                ptrOutCol,
                ptrOutRow,
                None,
                None,
                None,
                None,
                ct.c_float(0.0),
                ct.c_int32(rows),
                ct.c_int32(cols),
            )
Tim Dettmers's avatar
Tim Dettmers committed
2105
    else:
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
        lib.cdouble_rowcol_quant(
            ptrA,
            ptrRowStats,
            ptrColStats,
            ptrOutCol,
            ptrOutRow,
            None,
            None,
            None,
            None,
            ct.c_float(threshold),
            ct.c_int32(rows),
            ct.c_int32(cols),
        )
Tim Dettmers's avatar
Tim Dettmers committed
2120
2121
2122
2123
2124
2125
    post_call(prev_device)

    return out_row, out_col, row_stats, col_stats, coo_tensor


def transform(A, to_order, from_order='row', out=None, transpose=False, state=None, ld=None):
2126
    prev_device = pre_call(A.device)
Tim Dettmers's avatar
Tim Dettmers committed
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
    if state is None: state = (A.shape, from_order)
    else: from_order = state[1]
    if out is None: out, new_state = get_transform_buffer(state[0], A.dtype, A.device, to_order, state[1], transpose)
    else: new_state = (state[0], to_order) # (shape, order)

    shape = state[0]
    if len(shape) == 2:
        dim1 = ct.c_int32(shape[0])
        dim2 = ct.c_int32(shape[1])
    else:
2137
        dim1 = ct.c_int32(shape[0] * shape[1])
Tim Dettmers's avatar
Tim Dettmers committed
2138
2139
        dim2 = ct.c_int32(shape[2])

2140
    is_on_gpu([A, out])
Tim Dettmers's avatar
Tim Dettmers committed
2141
2142
2143
2144
2145
    if to_order == 'col32':
        if transpose:
            lib.ctransform_row2col32T(get_ptr(A), get_ptr(out), dim1, dim2)
        else:
            lib.ctransform_row2col32(get_ptr(A), get_ptr(out), dim1, dim2)
2146
    elif to_order == "col_turing":
Tim Dettmers's avatar
Tim Dettmers committed
2147
2148
2149
2150
        if transpose:
            lib.ctransform_row2turingT(get_ptr(A), get_ptr(out), dim1, dim2)
        else:
            lib.ctransform_row2turing(get_ptr(A), get_ptr(out), dim1, dim2)
2151
    elif to_order == "col_ampere":
Tim Dettmers's avatar
Tim Dettmers committed
2152
2153
2154
2155
        if transpose:
            lib.ctransform_row2ampereT(get_ptr(A), get_ptr(out), dim1, dim2)
        else:
            lib.ctransform_row2ampere(get_ptr(A), get_ptr(out), dim1, dim2)
2156
2157
    elif to_order == "row":
        if from_order == "col_turing":
Tim Dettmers's avatar
Tim Dettmers committed
2158
            lib.ctransform_turing2row(get_ptr(A), get_ptr(out), dim1, dim2)
2159
        elif from_order == "col_ampere":
Tim Dettmers's avatar
Tim Dettmers committed
2160
2161
2162
2163
            lib.ctransform_ampere2row(get_ptr(A), get_ptr(out), dim1, dim2)
    else:
        raise NotImplementedError(f'Transform function not implemented: From {from_order} to {to_order}')

2164
    post_call(prev_device)
Tim Dettmers's avatar
Tim Dettmers committed
2165
2166
2167

    return out, new_state

2168

Tim Dettmers's avatar
Tim Dettmers committed
2169
def spmm_coo(cooA, B, out=None):
2170
    if out is None:
2171
2172
2173
        out = torch.empty(
            (cooA.rows, B.shape[1]), device=B.device, dtype=B.dtype
        )
Tim Dettmers's avatar
Tim Dettmers committed
2174
2175
2176
2177
2178
2179
    nnz = cooA.nnz
    assert cooA.rowidx.numel() == nnz
    assert cooA.colidx.numel() == nnz
    assert cooA.values.numel() == nnz
    assert cooA.cols == B.shape[0]

2180
    transposed_B = False if B.is_contiguous() else True
Tim Dettmers's avatar
Tim Dettmers committed
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198

    ldb = B.stride()[(1 if transposed_B else 0)]
    ldc = B.shape[1]

    ptr = Cusparse_Context.get_instance().context

    ptrRowidx = get_ptr(cooA.rowidx)
    ptrColidx = get_ptr(cooA.colidx)
    ptrValues = get_ptr(cooA.values)
    ptrB = get_ptr(B)
    ptrC = get_ptr(out)
    cnnz = ct.c_int32(cooA.nnz)
    crowsA = ct.c_int32(cooA.rows)
    ccolsA = ct.c_int32(cooA.cols)
    ccolsB = ct.c_int32(B.shape[1])
    cldb = ct.c_int32(ldb)
    cldc = ct.c_int32(ldc)

2199
    is_on_gpu([cooA.rowidx, cooA.colidx, cooA.values, B, out])
Tim Dettmers's avatar
Tim Dettmers committed
2200
2201
2202
2203
    lib.cspmm_coo(ptr, ptrRowidx, ptrColidx, ptrValues, cnnz, crowsA, ccolsA, ccolsB, cldb, ptrB, cldc, ptrC, ct.c_bool(transposed_B))

    return out

2204

Tim Dettmers's avatar
Tim Dettmers committed
2205
def spmm_coo_very_sparse(cooA, B, dequant_stats=None, out=None):
2206
2207
2208
2209
    if out is None:
        out = torch.zeros(
            (cooA.rows, B.shape[1]), device=B.device, dtype=cooA.values.dtype
        )
Tim Dettmers's avatar
Tim Dettmers committed
2210
    nnz = cooA.nnz
2211
    prev_device = pre_call(B.device)
Tim Dettmers's avatar
Tim Dettmers committed
2212
2213
2214
    assert cooA.rowidx.numel() == nnz
    assert cooA.colidx.numel() == nnz
    assert cooA.values.numel() == nnz
2215
    assert cooA.cols == B.shape[0], f"{cooA.cols} vs {B.shape}"
Tim Dettmers's avatar
Tim Dettmers committed
2216

2217
    transposed_B = False if B.is_contiguous() else True
Tim Dettmers's avatar
Tim Dettmers committed
2218
2219
2220
2221
2222
2223
2224
2225
2226

    ldb = B.stride()[(1 if transposed_B else 0)]
    ldc = B.shape[1]

    values, counts = torch.unique(cooA.rowidx, return_counts=True)
    offset = counts.cumsum(0).int()
    max_count, max_idx = torch.sort(counts, descending=True)
    max_idx = max_idx.int()
    max_count = max_count.int()
2227
2228
2229
    assert (
        max_count[0] <= 32
    ), f"Current max count per row is 8 but found {max_count[0]}."
Tim Dettmers's avatar
Tim Dettmers committed
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
    assert B.dtype in [torch.float16, torch.int8]
    ptrOffset = get_ptr(offset)
    ptrMaxCount = get_ptr(max_count)
    ptrMaxIdx = get_ptr(max_idx)

    ptrRowidx = get_ptr(cooA.rowidx)
    ptrColidx = get_ptr(cooA.colidx)
    ptrValues = get_ptr(cooA.values)
    ptrB = get_ptr(B)
    ptrC = get_ptr(out)
    ptrDequantStats = get_ptr(dequant_stats)
    cnnz_rows = ct.c_int32(counts.numel())
    cnnz = ct.c_int32(cooA.nnz)
    crowsA = ct.c_int32(cooA.rows)
    ccolsA = ct.c_int32(cooA.cols)
    crowsB = ct.c_int32(B.shape[1])
    ccolsB = ct.c_int32(B.shape[1])
    cldb = ct.c_int32(ldb)
    cldc = ct.c_int32(ldc)

2250
    is_on_gpu([cooA.rowidx, cooA.colidx, cooA.values, B, out, dequant_stats])
Tim Dettmers's avatar
Tim Dettmers committed
2251
    if B.dtype == torch.float16:
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
        lib.cspmm_coo_very_sparse_naive_fp16(
            ptrMaxCount,
            ptrMaxIdx,
            ptrOffset,
            ptrRowidx,
            ptrColidx,
            ptrValues,
            ptrB,
            ptrC,
            ptrDequantStats,
            cnnz_rows,
            cnnz,
            crowsA,
            crowsB,
            ccolsB,
        )
Tim Dettmers's avatar
Tim Dettmers committed
2268
    elif B.dtype == torch.int8:
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
        lib.cspmm_coo_very_sparse_naive_int8(
            ptrMaxCount,
            ptrMaxIdx,
            ptrOffset,
            ptrRowidx,
            ptrColidx,
            ptrValues,
            ptrB,
            ptrC,
            ptrDequantStats,
            cnnz_rows,
            cnnz,
            crowsA,
            crowsB,
            ccolsB,
        )
    # else: assertion error
2286
    post_call(prev_device)
Tim Dettmers's avatar
Tim Dettmers committed
2287
2288
2289
2290
2291
2292

    return out


C = 127.0

2293
2294
2295

def vectorwise_quant(x, dim=1, quant_type="vector"):
    if quant_type == "linear":
Tim Dettmers's avatar
Tim Dettmers committed
2296
        max1 = torch.abs(x).max().float()
2297
        xq = torch.round(x / max1 * 127).to(torch.int8)
Tim Dettmers's avatar
Tim Dettmers committed
2298
        return xq, max1
2299
    elif quant_type in ["vector", "row"]:
Tim Dettmers's avatar
Tim Dettmers committed
2300
        max1 = torch.amax(torch.abs(x), dim=dim, keepdim=True)
2301
        xq = torch.round(x * (C / max1)).to(torch.int8)
Tim Dettmers's avatar
Tim Dettmers committed
2302
        return xq, max1
2303
    elif quant_type == "zeropoint":
Tim Dettmers's avatar
Tim Dettmers committed
2304
2305
2306
        dtype = x.dtype
        x = x.float()
        dyna = x.max() - x.min()
2307
2308
2309
        if dyna == 0:
            dyna = 1
        qx = 255.0 / dyna
Tim Dettmers's avatar
Tim Dettmers committed
2310
        minx = x.min()
2311
2312
        zpx = torch.round(minx * qx)
        x = torch.round(qx * x - zpx) + zpx
Tim Dettmers's avatar
Tim Dettmers committed
2313
        return x, qx
2314
    elif quant_type in ["vector-zeropoint", "row-zeropoint"]:
Tim Dettmers's avatar
Tim Dettmers committed
2315
2316
        dtype = x.dtype
        x = x.float()
2317
2318
2319
2320
2321
        dyna = torch.amax(x, dim=dim, keepdim=True) - torch.amin(
            x, dim=dim, keepdim=True
        )
        dyna[dyna == 0] = 1
        qx = 255.0 / dyna
Tim Dettmers's avatar
Tim Dettmers committed
2322
        minx = torch.amin(x, dim=dim, keepdim=True)
2323
2324
        zpx = torch.round(minx * qx)
        x = torch.round(qx * x - zpx) + zpx
Tim Dettmers's avatar
Tim Dettmers committed
2325
        return x, qx
2326
    elif quant_type == "truncated-vector":
Tim Dettmers's avatar
Tim Dettmers committed
2327
2328
2329
        with torch.no_grad():
            absx = torch.abs(x)
            max1 = torch.amax(absx, dim=dim, keepdim=True)
2330
2331
            max1 = max1 * 0.7
            idx = absx > max1.expand_as(absx)
Tim Dettmers's avatar
Tim Dettmers committed
2332
            sign = torch.sign(x[idx])
2333
2334
            x[idx] = max1.expand_as(absx)[idx] * sign
            xq = torch.round(x / max1 * C).to(torch.int8)
Tim Dettmers's avatar
Tim Dettmers committed
2335
        return xq, max1
2336
2337
2338
    else:
        return None

Tim Dettmers's avatar
Tim Dettmers committed
2339

2340
2341
2342
def vectorwise_dequant(xq, max1, quant_type="vector"):
    if quant_type == "vector":
        x = (xq / C * max1).to(torch.float32)
Tim Dettmers's avatar
Tim Dettmers committed
2343
        return x
2344
2345
    else:
        return None
Tim Dettmers's avatar
Tim Dettmers committed
2346

2347
2348
2349
2350

def vectorwise_mm_dequant(xq, S1, S2, dtype=torch.half, quant_type="vector"):
    if quant_type == "linear":
        norm = S1 * S2 / (C * C)
Tim Dettmers's avatar
Tim Dettmers committed
2351
        # double cast needed to prevent overflows
2352
2353
2354
2355
2356
2357
        return (xq.float() * norm).to(dtype)
    elif quant_type == "zeropoint":
        norm = 1.0 / (S1 * S2)
        return (xq.float() * norm).to(dtype)
    elif quant_type == "row-zeropoint":
        norm = 1.0 / (S1 * S2)
Tim Dettmers's avatar
Tim Dettmers committed
2358
        x = xq.float()
2359
2360
2361
2362
        if len(S1.shape) == 3 and len(x.shape) == 2:
            S1 = S1.squeeze(0)
        if len(S2.shape) == 3 and len(x.shape) == 2:
            S2 = S2.squeeze(0)
Tim Dettmers's avatar
Tim Dettmers committed
2363
2364
2365
2366
2367
        if len(S1.shape) == 2:
            x *= norm
        else:
            x *= norm
        return x.to(dtype)
2368
    elif quant_type == "vector-zeropoint":
Tim Dettmers's avatar
Tim Dettmers committed
2369
        x = xq.float()
2370
2371
2372
2373
        if len(S1.shape) == 3 and len(x.shape) == 2:
            S1 = S1.squeeze(0)
        if len(S2.shape) == 3 and len(x.shape) == 2:
            S2 = S2.squeeze(0)
Tim Dettmers's avatar
Tim Dettmers committed
2374
        if len(S1.shape) == 2:
2375
            x *= 1.0 / S1
Tim Dettmers's avatar
Tim Dettmers committed
2376
        else:
2377
2378
            x *= 1.0 / S1
        x *= 1.0 / S2.t()
Tim Dettmers's avatar
Tim Dettmers committed
2379
        return x.to(dtype)
2380
    elif quant_type == "row":
Tim Dettmers's avatar
Tim Dettmers committed
2381
        x = xq.float()
2382
2383
2384
2385
        if len(S1.shape) == 3 and len(x.shape) == 2:
            S1 = S1.squeeze(0)
        if len(S2.shape) == 3 and len(x.shape) == 2:
            S2 = S2.squeeze(0)
Tim Dettmers's avatar
Tim Dettmers committed
2386
        if len(S1.shape) == 2:
2387
            x *= S1 * S2 / (C * C)
Tim Dettmers's avatar
Tim Dettmers committed
2388
        else:
2389
            x *= S1 * S2 / (C * C)
Tim Dettmers's avatar
Tim Dettmers committed
2390
        return x.to(dtype)
2391
    elif quant_type in ["truncated-vector", "vector"]:
Tim Dettmers's avatar
Tim Dettmers committed
2392
        x = xq.float()
2393
2394
2395
2396
        if len(S1.shape) == 3 and len(x.shape) == 2:
            S1 = S1.squeeze(0)
        if len(S2.shape) == 3 and len(x.shape) == 2:
            S2 = S2.squeeze(0)
Tim Dettmers's avatar
Tim Dettmers committed
2397
        if len(S1.shape) == 2:
2398
            x *= S1 / C
Tim Dettmers's avatar
Tim Dettmers committed
2399
        else:
2400
2401
            x *= S1 / C
        x *= S2 / C
Tim Dettmers's avatar
Tim Dettmers committed
2402
        return x.to(dtype)
2403
2404
    else:
        return None
Tim Dettmers's avatar
Tim Dettmers committed
2405
2406
2407


def dequant_min_max(xq, A, B, SA, SB, dtype=torch.half):
2408
    offset = B.float().t().sum(0) * (SA[0] + SA[1])
Tim Dettmers's avatar
Tim Dettmers committed
2409
    x = xq.float()
2410
2411
    if len(xq.shape) == 2 and len(SB.shape) == 3:
        SB = SB.squeeze(0)
Tim Dettmers's avatar
Tim Dettmers committed
2412
    if len(SB.shape) == 2:
2413
        x *= SB.t() / 127
Tim Dettmers's avatar
Tim Dettmers committed
2414
    else:
2415
2416
2417
        x *= SB / 127
    x *= SA[1] / 127
    x += offset
Tim Dettmers's avatar
Tim Dettmers committed
2418
    return x.to(dtype)
2419

2420

2421
2422
2423
def extract_outliers(A, SA, idx):
    shapeA = SA[0]
    formatA = SA[1]
2424
2425
    assert formatA in ["col_turing", "col_ampere"]
    assert A.device.type == "cuda"
2426

2427
2428
2429
    out = torch.zeros(
        (shapeA[0], idx.numel()), dtype=torch.int8, device=A.device
    )
2430
2431
2432
2433
2434
2435
2436
2437

    idx_size = ct.c_int32(idx.numel())
    rows = ct.c_int32(shapeA[0])
    cols = ct.c_int32(shapeA[1])
    ptrA = get_ptr(A)
    ptrIdx = get_ptr(idx)
    ptrOut = get_ptr(out)

2438
    prev_device = pre_call(A.device)
2439
2440
    if formatA == 'col_turing':
        lib.cextractOutliers_turing(ptrA, ptrIdx, ptrOut, idx_size, rows, cols)
2441
    elif formatA == "col_ampere":
2442
        lib.cextractOutliers_ampere(ptrA, ptrIdx, ptrOut, idx_size, rows, cols)
2443
    post_call(prev_device)
2444
2445

    return out
Tim Dettmers's avatar
Tim Dettmers committed
2446
2447
2448
2449
2450

def pipeline_test(A, batch_size):
    out = torch.zeros_like(A)
    lib.cpipeline_test(get_ptr(A), get_ptr(out), ct.c_size_t(A.numel()), ct.c_size_t(batch_size))
    return out