2023-11-25 14:38:38 -07:00
|
|
|
# Adapted from turboderp exllama: https://github.com/turboderp/exllamav2
|
|
|
|
|
2024-05-28 03:51:31 -06:00
|
|
|
from dataclasses import dataclass
|
|
|
|
from typing import Optional
|
2023-11-25 14:38:38 -07:00
|
|
|
import torch
|
|
|
|
import torch.nn as nn
|
|
|
|
|
2024-01-26 08:27:44 -07:00
|
|
|
from loguru import logger
|
2023-11-25 14:38:38 -07:00
|
|
|
|
2024-05-28 03:51:31 -06:00
|
|
|
from text_generation_server.layers.exl2 import Exl2Weight
|
|
|
|
from text_generation_server.layers.gptq import GPTQWeight
|
2024-07-20 11:02:04 -06:00
|
|
|
from text_generation_server.utils.log import log_master
|
2024-05-28 03:51:31 -06:00
|
|
|
|
2023-11-25 14:38:38 -07:00
|
|
|
try:
|
2024-08-14 03:58:08 -06:00
|
|
|
from exllamav2.ext import exllamav2_ext
|
|
|
|
|
|
|
|
make_q_matrix = exllamav2_ext.make_q_matrix
|
|
|
|
gemm_half_q_half = exllamav2_ext.gemm_half_q_half
|
2023-11-25 14:38:38 -07:00
|
|
|
except ImportError:
|
2024-07-20 11:02:04 -06:00
|
|
|
log_master(logger.warning, "exllamav2_kernels not installed.")
|
2023-11-25 14:38:38 -07:00
|
|
|
raise
|
|
|
|
|
|
|
|
# Dummy tensor to pass instead of g_idx since there is no way to pass "None" to a C++ extension
|
|
|
|
none_tensor = torch.empty((1, 1), device="meta")
|
|
|
|
|
2023-12-11 06:49:52 -07:00
|
|
|
|
2024-05-28 03:51:31 -06:00
|
|
|
@dataclass
|
|
|
|
class _ExtraTensors:
|
|
|
|
"""Additional generated quantizer tensors."""
|
|
|
|
|
|
|
|
q_group_map: Optional[torch.Tensor] = None
|
|
|
|
q_invperm: Optional[torch.Tensor] = None
|
|
|
|
q_perm: Optional[torch.Tensor] = None
|
|
|
|
|
|
|
|
|
2023-11-25 14:38:38 -07:00
|
|
|
def ext_gemm_half_q_half(x, q_handle, q4_width, force_cuda):
|
|
|
|
"""Matrix multiplication, returns x @ q4"""
|
|
|
|
output_shape = x.shape[:-1] + (q4_width,)
|
|
|
|
x = x.view(-1, x.shape[-1])
|
2023-12-11 06:49:52 -07:00
|
|
|
output = torch.empty((x.shape[0], q4_width), dtype=torch.half, device=x.device)
|
2023-11-25 14:38:38 -07:00
|
|
|
gemm_half_q_half(x, q_handle, output, force_cuda)
|
|
|
|
return output.view(output_shape)
|
|
|
|
|
2023-12-11 06:49:52 -07:00
|
|
|
|
2024-05-28 03:51:31 -06:00
|
|
|
def make_group_map(q_groups: torch.Tensor, num_qrows: int):
|
2023-12-21 09:25:22 -07:00
|
|
|
gr = q_groups.tolist()
|
|
|
|
group_map = []
|
|
|
|
num_groups = len(gr) // 2
|
|
|
|
|
|
|
|
for i in range(num_groups):
|
|
|
|
bits = gr[i * 2]
|
|
|
|
if i < num_groups - 1:
|
|
|
|
qrows = gr[i * 2 + 3] - gr[i * 2 + 1]
|
|
|
|
else:
|
|
|
|
qrows = num_qrows - gr[i * 2 + 1]
|
|
|
|
rows = qrows * 32 // bits
|
|
|
|
for j in range(rows):
|
|
|
|
group_map += [i]
|
|
|
|
group_map += [rows - j]
|
|
|
|
|
|
|
|
return torch.tensor(group_map, dtype=torch.short, device=q_groups.device)
|
|
|
|
|
|
|
|
|
|
|
|
# Create Q matrix
|
|
|
|
|
|
|
|
|
2024-05-28 03:51:31 -06:00
|
|
|
def ext_make_q_matrix(
|
|
|
|
w: Exl2Weight | GPTQWeight,
|
|
|
|
extra: _ExtraTensors,
|
|
|
|
temp_dq,
|
|
|
|
key: Optional[str] = None,
|
|
|
|
):
|
2023-11-25 14:38:38 -07:00
|
|
|
"""
|
2023-12-11 06:49:52 -07:00
|
|
|
Create Q matrix
|
2023-11-25 14:38:38 -07:00
|
|
|
"""
|
2024-08-14 03:58:08 -06:00
|
|
|
# max_dq_size = 512*(1024**2)
|
|
|
|
# max_dq_rows = max_dq_size // out_features[0]
|
|
|
|
max_dq_rows = 0
|
|
|
|
|
2023-11-25 14:38:38 -07:00
|
|
|
# EXL2
|
2024-05-28 03:51:31 -06:00
|
|
|
if isinstance(w, Exl2Weight):
|
|
|
|
extra.q_group_map = make_group_map(w.q_groups, w.q_weight.shape[0])
|
|
|
|
extra.q_perm = torch.argsort(w.q_invperm).short()
|
2023-12-21 09:25:22 -07:00
|
|
|
|
2023-12-11 06:49:52 -07:00
|
|
|
return make_q_matrix(
|
2024-05-28 03:51:31 -06:00
|
|
|
w.q_weight,
|
|
|
|
extra.q_perm,
|
|
|
|
w.q_invperm,
|
|
|
|
w.q_scale,
|
|
|
|
w.q_scale_max,
|
|
|
|
w.q_groups,
|
|
|
|
extra.q_group_map,
|
2024-08-14 03:58:08 -06:00
|
|
|
none_tensor, # zeros
|
|
|
|
none_tensor, # scales
|
|
|
|
none_tensor, # g_idx
|
|
|
|
none_tensor, # bias
|
2023-12-11 06:49:52 -07:00
|
|
|
temp_dq,
|
2024-08-14 03:58:08 -06:00
|
|
|
max_dq_rows,
|
2023-12-11 06:49:52 -07:00
|
|
|
)
|
2023-11-25 14:38:38 -07:00
|
|
|
# GPTQ
|
2024-05-28 03:51:31 -06:00
|
|
|
elif isinstance(w, GPTQWeight):
|
|
|
|
if w.scales.dtype == torch.float:
|
|
|
|
w.scales = w.scales.half()
|
2023-11-25 14:38:38 -07:00
|
|
|
|
|
|
|
# GPTQ with g_idx (act_order)
|
2024-05-28 03:51:31 -06:00
|
|
|
if w.g_idx is not None and not (w.g_idx == 0).all().item():
|
|
|
|
extra.q_perm = torch.empty(
|
|
|
|
(w.qweight.shape[0] * 8,),
|
2023-12-11 06:49:52 -07:00
|
|
|
dtype=torch.short,
|
2024-05-28 03:51:31 -06:00
|
|
|
device=w.qweight.device,
|
2023-12-11 06:49:52 -07:00
|
|
|
)
|
2024-05-28 03:51:31 -06:00
|
|
|
extra.q_invperm = torch.empty_like(extra.q_perm)
|
2023-11-25 14:38:38 -07:00
|
|
|
# make_q4 segfaults if g_idx is not on cpu in the act-order case. In the non act-order case, None needs to be passed for g_idx.
|
2023-12-11 06:49:52 -07:00
|
|
|
return make_q_matrix(
|
2024-05-28 03:51:31 -06:00
|
|
|
w.qweight,
|
|
|
|
extra.q_perm,
|
|
|
|
extra.q_invperm,
|
2024-08-14 03:58:08 -06:00
|
|
|
none_tensor, # q_scale
|
|
|
|
none_tensor, # q_scale_max
|
|
|
|
none_tensor, # q_groups
|
|
|
|
none_tensor, # q_group_map
|
2024-05-28 03:51:31 -06:00
|
|
|
w.qzeros,
|
|
|
|
w.scales,
|
|
|
|
w.g_idx.cpu(),
|
2024-08-14 03:58:08 -06:00
|
|
|
none_tensor, # bias
|
2023-12-11 06:49:52 -07:00
|
|
|
temp_dq,
|
2024-08-14 03:58:08 -06:00
|
|
|
max_dq_rows,
|
2023-12-11 06:49:52 -07:00
|
|
|
)
|
2023-11-25 14:38:38 -07:00
|
|
|
# GPTQ without g_idx
|
|
|
|
else:
|
2023-12-11 06:49:52 -07:00
|
|
|
return make_q_matrix(
|
2024-05-28 03:51:31 -06:00
|
|
|
w.qweight,
|
2024-08-14 03:58:08 -06:00
|
|
|
none_tensor, # q_perm
|
|
|
|
none_tensor, # q_invperm
|
|
|
|
none_tensor, # q_scale
|
|
|
|
none_tensor, # q_scale_max
|
|
|
|
none_tensor, # q_groups
|
|
|
|
none_tensor, # q_group_map
|
2024-05-28 03:51:31 -06:00
|
|
|
w.qzeros,
|
|
|
|
w.scales,
|
2024-08-14 03:58:08 -06:00
|
|
|
none_tensor, # g_idx
|
|
|
|
none_tensor, # bias
|
2023-12-11 06:49:52 -07:00
|
|
|
temp_dq,
|
2024-08-14 03:58:08 -06:00
|
|
|
max_dq_rows,
|
2023-12-11 06:49:52 -07:00
|
|
|
)
|
2024-05-13 04:44:30 -06:00
|
|
|
else:
|
|
|
|
RuntimeError("Cannot create handle")
|
2023-12-11 06:49:52 -07:00
|
|
|
|
2023-11-25 14:38:38 -07:00
|
|
|
|
|
|
|
DEVICE = None
|
|
|
|
LAYERS = []
|
|
|
|
|
|
|
|
|
|
|
|
def set_device(device):
|
|
|
|
global DEVICE
|
|
|
|
DEVICE = device
|
|
|
|
|
|
|
|
|
2023-12-18 08:07:05 -07:00
|
|
|
def create_exllama_buffers(max_total_tokens: int):
|
2024-05-28 03:51:31 -06:00
|
|
|
global LAYERS, DEVICE
|
|
|
|
|
2024-06-05 02:45:47 -06:00
|
|
|
# No need to initialize scratch space if there are no layers
|
|
|
|
# that use ExLLamav2.
|
|
|
|
if len(LAYERS) == 0:
|
|
|
|
return
|
|
|
|
|
2024-05-28 03:51:31 -06:00
|
|
|
# Find the size of the scratch space.
|
|
|
|
scratch_bytes = max(
|
2024-05-31 10:01:43 -06:00
|
|
|
layer.scratch_space_fixed(max_input_len=max_total_tokens, max_batch_size=1)
|
|
|
|
for layer in LAYERS
|
2024-05-28 03:51:31 -06:00
|
|
|
)
|
|
|
|
temp_dq = ExLlamaV2DeviceTensors(DEVICE, scratch_bytes)
|
2023-11-25 14:38:38 -07:00
|
|
|
|
|
|
|
for layer in LAYERS:
|
|
|
|
layer.post_init(temp_dq)
|
|
|
|
|
|
|
|
|
|
|
|
class QuantLinear(nn.Module):
|
|
|
|
QUANT_TYPE = "exllamav2"
|
|
|
|
|
|
|
|
"""Linear layer implementation with per-group 4-bit quantization of the weights"""
|
|
|
|
|
2024-05-28 03:51:31 -06:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
weight: Exl2Weight | GPTQWeight,
|
|
|
|
bias: torch.Tensor,
|
|
|
|
):
|
2023-11-25 14:38:38 -07:00
|
|
|
super().__init__()
|
2024-05-28 03:51:31 -06:00
|
|
|
|
2023-11-25 14:38:38 -07:00
|
|
|
self.q_handle = None
|
2024-05-28 03:51:31 -06:00
|
|
|
self.q_tensors = weight
|
|
|
|
self.extra_tensors = _ExtraTensors()
|
|
|
|
|
|
|
|
if isinstance(weight, Exl2Weight):
|
|
|
|
self.infeatures = weight.q_invperm.shape[0]
|
|
|
|
self.outfeatures = weight.q_weight.shape[1]
|
|
|
|
elif isinstance(weight, GPTQWeight):
|
|
|
|
if weight.bits != 4:
|
|
|
|
raise ValueError(
|
|
|
|
f"Exllamav2 kernel supports only bits=4, requested bits={weight.bits}. Something is wrong in the model initialization."
|
|
|
|
)
|
|
|
|
|
|
|
|
self.infeatures = weight.qweight.shape[0] // weight.bits * 32
|
|
|
|
self.outfeatures = weight.qweight.shape[1]
|
|
|
|
|
2023-12-11 06:49:52 -07:00
|
|
|
self.padding = -self.outfeatures % 32
|
2023-11-25 14:38:38 -07:00
|
|
|
self.outfeatures = self.outfeatures + self.padding
|
|
|
|
|
2024-05-28 03:51:31 -06:00
|
|
|
self.device = weight.device
|
2023-11-25 14:38:38 -07:00
|
|
|
self.bias = bias if bias is not None else None
|
|
|
|
|
2024-05-28 03:51:31 -06:00
|
|
|
global LAYERS
|
2023-11-25 14:38:38 -07:00
|
|
|
LAYERS.append(self)
|
|
|
|
|
|
|
|
def post_init(self, temp_dq):
|
2024-05-28 03:51:31 -06:00
|
|
|
device = self.q_tensors.device
|
|
|
|
assert device.type == "cuda"
|
|
|
|
assert device.index is not None
|
2023-11-25 14:38:38 -07:00
|
|
|
temp_dq = temp_dq.get_scratch_slice(self.temp_dq_size())
|
2024-01-26 06:00:29 -07:00
|
|
|
|
|
|
|
# We NEED to keep a pointer on Python side, otherwise the garbage collector will mess with us,
|
|
|
|
# and `Memory access fault by GPU node-2` will EAT you.
|
|
|
|
self.temp_dq = temp_dq
|
2024-05-28 03:51:31 -06:00
|
|
|
self.q_handle = ext_make_q_matrix(self.q_tensors, self.extra_tensors, temp_dq)
|
2023-12-11 06:49:52 -07:00
|
|
|
|
|
|
|
def forward(self, x, force_cuda=False):
|
2023-11-25 14:38:38 -07:00
|
|
|
output = ext_gemm_half_q_half(x, self.q_handle, self.outfeatures, force_cuda)
|
|
|
|
|
|
|
|
if self.bias is not None:
|
|
|
|
output.add_(self.bias)
|
|
|
|
return output
|
2023-12-11 06:49:52 -07:00
|
|
|
|
2023-11-25 14:38:38 -07:00
|
|
|
def temp_dq_size(self):
|
|
|
|
return self.infeatures * self.outfeatures * 2 + 128
|
2023-12-11 06:49:52 -07:00
|
|
|
|
2023-11-25 14:38:38 -07:00
|
|
|
def temp_fwd_size(self, max_input_len, max_batch_size):
|
|
|
|
return self.outfeatures * max_input_len * max_batch_size * 4 + 128
|
2023-12-11 06:49:52 -07:00
|
|
|
|
2024-05-31 10:01:43 -06:00
|
|
|
def scratch_space_fixed(self, max_input_len, max_batch_size):
|
2023-11-25 14:38:38 -07:00
|
|
|
return self.temp_dq_size() + self.temp_fwd_size(max_input_len, max_batch_size)
|
2023-12-11 06:49:52 -07:00
|
|
|
|
|
|
|
|
2023-11-25 14:38:38 -07:00
|
|
|
class ExLlamaV2DeviceTensors:
|
|
|
|
|
|
|
|
device_idx: int
|
|
|
|
scratch_bytes: int
|
|
|
|
scratch_idx: int
|
|
|
|
scratch: torch.tensor = None
|
|
|
|
|
|
|
|
def __init__(self, device, scratch_bytes):
|
|
|
|
self.device = device
|
|
|
|
self.scratch_bytes = scratch_bytes
|
2023-12-11 06:49:52 -07:00
|
|
|
|
2023-11-25 14:38:38 -07:00
|
|
|
def prepare(self):
|
2023-12-11 06:49:52 -07:00
|
|
|
self.scratch = torch.empty(
|
|
|
|
(self.scratch_bytes // 2,), dtype=torch.half, device=self.device
|
|
|
|
)
|
2023-11-25 14:38:38 -07:00
|
|
|
|
|
|
|
def get_scratch_slice(self, size_bytes):
|
|
|
|
|
2023-12-11 06:49:52 -07:00
|
|
|
if self.scratch is None:
|
|
|
|
self.prepare()
|
2023-11-25 14:38:38 -07:00
|
|
|
|
|
|
|
size_bytes = ((size_bytes + 127) // 128) * 128
|
|
|
|
size_half = size_bytes // 2
|
|
|
|
scratch_slice = self.scratch.narrow(0, 0, size_half)
|
|
|
|
return scratch_slice
|