|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +import math, struct |
| 8 | +from typing import Callable |
| 9 | + |
| 10 | +import fbgemm_gpu |
| 11 | +import numpy as np |
| 12 | +import torch |
| 13 | + |
| 14 | +# pyre-fixme[16]: Module `fbgemm_gpu` has no attribute `open_source`. |
| 15 | +open_source: bool = getattr(fbgemm_gpu, "open_source", False) |
| 16 | + |
| 17 | +try: |
| 18 | + # pyre-ignore[21] |
| 19 | + from fbgemm_gpu import open_source # noqa: F401 |
| 20 | + |
| 21 | +except Exception: |
| 22 | + if torch.version.hip: |
| 23 | + torch.ops.load_library("//deeplearning/fbgemm/fbgemm_gpu:sparse_ops_hip") |
| 24 | + else: |
| 25 | + torch.ops.load_library("//deeplearning/fbgemm/fbgemm_gpu:sparse_ops") |
| 26 | + |
| 27 | + torch.ops.load_library("//deeplearning/fbgemm/fbgemm_gpu:sparse_ops_cpu") |
| 28 | + |
| 29 | +# Eigen/Python round 0.5 away from 0, Numpy rounds to even |
| 30 | +round_to_nearest: Callable[[np.ndarray], np.ndarray] = np.vectorize(round) |
| 31 | + |
| 32 | + |
| 33 | +def bytes_to_floats(byte_matrix: np.ndarray) -> np.ndarray: |
| 34 | + floats = np.empty([np.shape(byte_matrix)[0], 1], dtype=np.float32) |
| 35 | + for i, byte_values in enumerate(byte_matrix): |
| 36 | + (floats[i],) = struct.unpack("f", bytearray(byte_values)) |
| 37 | + return floats |
| 38 | + |
| 39 | + |
| 40 | +def floats_to_bytes(floats: np.ndarray) -> np.ndarray: |
| 41 | + byte_matrix = np.empty([np.shape(floats)[0], 4], dtype=np.uint8) |
| 42 | + for i, value in enumerate(floats): |
| 43 | + assert isinstance(value, np.float32), (value, floats) |
| 44 | + as_bytes = struct.pack("f", value) |
| 45 | + # In Python3 bytes will be a list of int, in Python2 a list of string |
| 46 | + if isinstance(as_bytes[0], int): |
| 47 | + byte_matrix[i] = list(as_bytes) |
| 48 | + else: |
| 49 | + byte_matrix[i] = list(map(ord, as_bytes)) |
| 50 | + return byte_matrix |
| 51 | + |
| 52 | + |
| 53 | +def bytes_to_half_floats(byte_matrix: np.ndarray) -> np.ndarray: |
| 54 | + floats = np.empty([np.shape(byte_matrix)[0], 1], dtype=np.float16) |
| 55 | + for i, byte_values in enumerate(byte_matrix): |
| 56 | + (floats[i],) = np.frombuffer( |
| 57 | + memoryview(byte_values).tobytes(), dtype=np.float16 |
| 58 | + ) |
| 59 | + return floats |
| 60 | + |
| 61 | + |
| 62 | +def half_floats_to_bytes(floats: np.ndarray) -> np.ndarray: |
| 63 | + byte_matrix = np.empty([np.shape(floats)[0], 2], dtype=np.uint8) |
| 64 | + for i, value in enumerate(floats): |
| 65 | + assert isinstance(value, np.float16), (value, floats) |
| 66 | + byte_matrix[i] = np.frombuffer( |
| 67 | + memoryview(value.tobytes()).tobytes(), dtype=np.uint8 |
| 68 | + ) |
| 69 | + return byte_matrix |
| 70 | + |
| 71 | + |
| 72 | +def fused_rowwise_8bit_quantize_reference(data: np.ndarray) -> np.ndarray: |
| 73 | + minimum = np.min(data, axis=-1, keepdims=True) |
| 74 | + maximum = np.max(data, axis=-1, keepdims=True) |
| 75 | + span = maximum - minimum |
| 76 | + bias = minimum |
| 77 | + scale = span / 255.0 |
| 78 | + inverse_scale = 255.0 / (span + 1e-8) |
| 79 | + quantized_data = round_to_nearest((data - bias) * inverse_scale) |
| 80 | + scale_bytes = floats_to_bytes(scale.reshape(-1)) |
| 81 | + scale_bytes = scale_bytes.reshape(data.shape[:-1] + (scale_bytes.shape[-1],)) |
| 82 | + bias_bytes = floats_to_bytes(bias.reshape(-1)) |
| 83 | + bias_bytes = bias_bytes.reshape(data.shape[:-1] + (bias_bytes.shape[-1],)) |
| 84 | + return np.concatenate([quantized_data, scale_bytes, bias_bytes], axis=-1) |
| 85 | + |
| 86 | + |
| 87 | +def fused_rowwise_8bit_dequantize_reference(fused_quantized: np.ndarray) -> np.ndarray: |
| 88 | + scale = bytes_to_floats(fused_quantized[..., -8:-4].astype(np.uint8).reshape(-1, 4)) |
| 89 | + scale = scale.reshape(fused_quantized.shape[:-1] + (scale.shape[-1],)) |
| 90 | + bias = bytes_to_floats(fused_quantized[..., -4:].astype(np.uint8).reshape(-1, 4)) |
| 91 | + bias = bias.reshape(fused_quantized.shape[:-1] + (bias.shape[-1],)) |
| 92 | + quantized_data = fused_quantized[..., :-8] |
| 93 | + return quantized_data * scale + bias |
| 94 | + |
| 95 | + |
| 96 | +def fused_rowwise_8bit_dequantize_reference_half( |
| 97 | + fused_quantized: np.ndarray, |
| 98 | +) -> np.ndarray: |
| 99 | + scale = bytes_to_half_floats( |
| 100 | + fused_quantized[..., -8:-4].astype(np.uint8).reshape(-1, 4) |
| 101 | + ) |
| 102 | + scale = scale.reshape(fused_quantized.shape[:-1] + (scale.shape[-1],)) |
| 103 | + bias = bytes_to_half_floats( |
| 104 | + fused_quantized[..., -4:].astype(np.uint8).reshape(-1, 4) |
| 105 | + ) |
| 106 | + bias = bias.reshape(fused_quantized.shape[:-1] + (bias.shape[-1],)) |
| 107 | + quantized_data = fused_quantized[..., :-8] |
| 108 | + return quantized_data * scale + bias |
| 109 | + |
| 110 | + |
| 111 | +def fused_rowwise_nbit_quantize_reference(data: np.ndarray, bit: int) -> np.ndarray: |
| 112 | + minimum = np.min(data, axis=1).astype(np.float16).astype(np.float32) |
| 113 | + maximum = np.max(data, axis=1) |
| 114 | + span = maximum - minimum |
| 115 | + qmax = (1 << bit) - 1 |
| 116 | + scale = (span / qmax).astype(np.float16).astype(np.float32) |
| 117 | + bias = np.zeros(data.shape[0]) |
| 118 | + quantized_data = np.zeros(data.shape).astype(np.uint8) |
| 119 | + |
| 120 | + for i in range(data.shape[0]): |
| 121 | + bias[i] = minimum[i] |
| 122 | + inverse_scale = 1.0 if scale[i] == 0.0 else 1 / scale[i] |
| 123 | + if scale[i] == 0.0 or math.isinf(inverse_scale): |
| 124 | + scale[i] = 1.0 |
| 125 | + inverse_scale = 1.0 |
| 126 | + quantized_data[i] = np.clip( |
| 127 | + np.round((data[i, :] - minimum[i]) * inverse_scale), 0, qmax |
| 128 | + ) |
| 129 | + |
| 130 | + # pack |
| 131 | + assert 8 % bit == 0 |
| 132 | + num_elem_per_byte = 8 // bit |
| 133 | + packed_dim = (data.shape[1] + num_elem_per_byte - 1) // num_elem_per_byte |
| 134 | + packed_data = np.zeros([data.shape[0], packed_dim]).astype(np.uint8) |
| 135 | + for i in range(data.shape[0]): |
| 136 | + for j in range(data.shape[1]): |
| 137 | + if j % num_elem_per_byte == 0: |
| 138 | + packed_data[i, j // num_elem_per_byte] = quantized_data[i, j] |
| 139 | + else: |
| 140 | + packed_data[i, j // num_elem_per_byte] += quantized_data[i, j] << ( |
| 141 | + (j % num_elem_per_byte) * bit |
| 142 | + ) |
| 143 | + |
| 144 | + scale_bytes = half_floats_to_bytes(scale.astype(np.float16)) |
| 145 | + bias_bytes = half_floats_to_bytes(bias.astype(np.float16)) |
| 146 | + return np.concatenate([packed_data, scale_bytes, bias_bytes], axis=1) |
| 147 | + |
| 148 | + |
| 149 | +def fused_rowwise_nbit_quantize_dequantize_reference( |
| 150 | + data: np.ndarray, bit: int |
| 151 | +) -> np.ndarray: |
| 152 | + fused_quantized = fused_rowwise_nbit_quantize_reference(data, bit) |
| 153 | + scale = bytes_to_half_floats(fused_quantized[:, -4:-2].astype(np.uint8)).astype( |
| 154 | + np.float32 |
| 155 | + ) |
| 156 | + bias = bytes_to_half_floats(fused_quantized[:, -2:].astype(np.uint8)).astype( |
| 157 | + np.float32 |
| 158 | + ) |
| 159 | + quantized_data = fused_quantized[:, :-4] |
| 160 | + |
| 161 | + # unpack |
| 162 | + packed_dim = fused_quantized.shape[1] - 4 |
| 163 | + assert 8 % bit == 0 |
| 164 | + num_elem_per_byte = 8 // bit |
| 165 | + assert packed_dim == ((data.shape[1] + num_elem_per_byte - 1) // num_elem_per_byte) |
| 166 | + unpacked_data = np.zeros(data.shape).astype(np.uint8) |
| 167 | + for i in range(data.shape[0]): |
| 168 | + for j in range(data.shape[1]): |
| 169 | + unpacked_data[i, j] = ( |
| 170 | + quantized_data[i, j // num_elem_per_byte] |
| 171 | + >> ((j % num_elem_per_byte) * bit) |
| 172 | + ) & ((1 << bit) - 1) |
| 173 | + |
| 174 | + return scale * unpacked_data + bias |
0 commit comments