Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions gptqmodel/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,8 @@ def quantize(
backend: Optional[BACKEND] = BACKEND.AUTO,
# Experimental: enables the buffering of fwd inputs to cpu, slower than non-buffered, may reduce vram usage
buffered_fwd: bool = False,
# torch/cuda GC is auto enabled to reduce vram usage: disable to for small models or you know there is no possibility of oom due to vram to accelerate quantization
auto_gc: bool = True,
) -> List[Dict[str, str]]:
if self.quantized:
raise EnvironmentError("quantize() is called a model that is already quantized")
Expand Down Expand Up @@ -547,7 +549,8 @@ def store_lm_head_input_hook(_, args, kwargs):
if module is not None:
move_to(module, ori_outside_layer_module_devices[module_name])

torch_empty_cache()
if auto_gc:
torch_empty_cache()

layer_modules = self.layer_modules

Expand Down Expand Up @@ -720,7 +723,8 @@ def tmp(_, inp: Tuple[torch.Tensor, ...], out: torch.Tensor):
subset[name].forward_hook = None

if index == len(layer_modules) - 1:
torch_empty_cache()
if auto_gc:
torch_empty_cache()

for name_index, name in enumerate(subset):
layer_name = self.lm_head if is_lm_head else f"{self.layers_node}.{i}.{name}"
Expand Down Expand Up @@ -810,7 +814,8 @@ def tmp(_, inp: Tuple[torch.Tensor, ...], out: torch.Tensor):
del layer_input
del additional_layer_inputs
if num_batches > 1 and j == num_batches - 1:
torch_empty_cache()
if auto_gc:
torch_empty_cache()

if not is_lm_head:
layers[i] = move_to(layer, CPU)
Expand All @@ -825,7 +830,8 @@ def tmp(_, inp: Tuple[torch.Tensor, ...], out: torch.Tensor):
[],
) # TODO: is it really OK to cache only the first positional argument?

torch_empty_cache()
if auto_gc:
torch_empty_cache()

logger.info(f"Quantization summary:\n{self.quant_log}")
for module_log in self.quant_log:
Expand Down Expand Up @@ -858,7 +864,8 @@ def tmp(_, inp: Tuple[torch.Tensor, ...], out: torch.Tensor):
self.model.config.use_cache = forward_pass_use_cache

self.quantized = True
torch_empty_cache()
if auto_gc:
torch_empty_cache()

return self.quant_log

Expand Down
73 changes: 42 additions & 31 deletions gptqmodel/nn_modules/qlinear/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ def __init__(self,
else:
raise ValueError("Unsupported weight_dtype. Only int16 and int32 are supported.")

# pack_factor is only used for bits 2, 4, and 8. bit3 3 does not use this variable.
self.pack_factor = self.pack_dtype_bits // self.bits
_, err = self._validate(bits=bits, group_size=group_size, desc_act=desc_act, sym=sym, in_features=in_features, out_features=out_features, pack_dtype=pack_dtype)
if err:
Expand Down Expand Up @@ -299,52 +300,62 @@ def pack(self, linear, scales, zeros, g_idx=None):
intweight = intweight.numpy().astype(self.pack_np_math_dtype)

qweight = np.zeros((intweight.shape[0] // self.pack_dtype_bits * self.bits, intweight.shape[1]),
dtype=self.pack_np_dtype)
dtype=self.pack_np_math_dtype)
if self.bits in [2, 4, 8]:
for row in range(qweight.shape[0]):
for j in range(self.pack_factor):
qweight[row] |= intweight[row * self.pack_factor + j] << (self.bits * j)
elif self.bits == 3:
for row in range(qweight.shape[0]):
row_offset = row * 10 # Cache row * 10
row_offset_plus_10 = row_offset + 10 # Cache row * 10 + 10
for j in range(10):
qweight[row] |= intweight[row_offset + j] << (3 * j)
qweight[row] |= intweight[row_offset_plus_10] << 30
i = 0
row = 0
while row < qweight.shape[0]:
for j in range(i, i + 10):
qweight[row] |= intweight[j] << (3 * (j - i))
i += 10
qweight[row] |= intweight[i] << 30
row += 1
qweight[row] |= (intweight[i] >> 2) & 1
i += 1
for j in range(i, i + 10):
qweight[row] |= intweight[j] << (3 * (j - i) + 1)
i += 10
qweight[row] |= intweight[i] << 31
row += 1
qweight[row] |= (intweight[row_offset_plus_10] >> 2) & 1
for j in range(10):
qweight[row] |= intweight[row_offset + j] << (3 * j + 1)
qweight[row] |= intweight[row_offset_plus_10] << 31
qweight[row] |= (intweight[i] >> 1) & 0x3
i += 1
for j in range(i, i + 10):
qweight[row] |= intweight[j] << (3 * (j - i) + 2)
i += 10
row += 1
qweight[row] |= (intweight[row_offset_plus_10] >> 1) & 0x3
for j in range(10):
qweight[row] |= intweight[row_offset + j] << (3 * j + 2)

self.qweight = t.from_numpy(qweight.astype(self.pack_np_dtype))

zeros = zeros.numpy().astype(self.pack_np_math_dtype)
qzeros = np.zeros((zeros.shape[0], zeros.shape[1] // self.pack_dtype_bits * self.bits),
dtype=self.pack_np_math_dtype)
qzeros = np.zeros((zeros.shape[0], zeros.shape[1] // self.pack_dtype_bits * self.bits), dtype=self.pack_np_math_dtype)
if self.bits in [2, 4, 8]:
for col in range(qzeros.shape[1]):
for j in range(self.pack_factor):
qzeros[:, col] |= zeros[:, col * self.pack_factor + j] << (self.bits * j)
elif self.bits == 3:
for col in range(qzeros.shape[1]):
col_offset = col * 10 # Cache col * 10
col_offset_plus_10 = col_offset + 10 # Cache col * 10 + 10
for j in range(10):
qzeros[:, col] |= zeros[:, col_offset + j] << (3 * j)
qzeros[:, col] |= zeros[:, col_offset_plus_10] << 30
col += 1
qzeros[:, col] |= (zeros[:, col_offset_plus_10] >> 2) & 1
for j in range(10):
qzeros[:, col] |= zeros[:, col_offset + j] << (3 * j + 1)
qzeros[:, col] |= zeros[:, col_offset_plus_10] << 31
col += 1
qzeros[:, col] |= (zeros[:, col_offset_plus_10] >> 1) & 0x3
for j in range(10):
qzeros[:, col] |= zeros[:, col_offset + j] << (3 * j + 2)
i = 0
col = 0
for j in range(i, i + 10):
qzeros[:, col] |= zeros[:, j] << (3 * (j - i))
i += 10
qzeros[:, col] |= zeros[:, i] << 30
col += 1
qzeros[:, col] |= (zeros[:, i] >> 2) & 1
i += 1
for j in range(i, i + 10):
qzeros[:, col] |= zeros[:, j] << (3 * (j - i) + 1)
i += 10
qzeros[:, col] |= zeros[:, i] << 31
col += 1
qzeros[:, col] |= (zeros[:, i] >> 1) & 0x3
i += 1
for j in range(i, i + 10):
qzeros[:, col] |= zeros[:, j] << (3 * (j - i) + 2)
i += 10
col += 1

self.qzeros = t.from_numpy(qzeros.astype(self.pack_np_dtype))
39 changes: 35 additions & 4 deletions gptqmodel/utils/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,15 +335,46 @@ def convert_gptq_v1_to_v2_format(
elif cfg.pack_dtype == torch.int8:
submodule.qzeros.data += 0b01010101
elif cfg.bits == 3:
raise Exception("FIX ME")
# range 0 offset
if cfg.pack_dtype == torch.int64:
offset = 0b0010010010010010010010010010010000100100100100100100100100100100
elif cfg.pack_dtype == torch.int32:
offset = 0b00100100100100100100100100100100
elif cfg.pack_dtype == torch.int16:
offset = 0b0010010010010010
elif cfg.pack_dtype == torch.int8:
offset = 0b00100100

submodule.qzeros.data[:, range(0, submodule.qzeros.data.shape[1], 3)] += (
0b00100100100100100100100100100100
offset
)

# range 1 offset
if cfg.pack_dtype == torch.int64:
offset = 0b1001001001001001001001001001001010010010010010010010010010010010
elif cfg.pack_dtype == torch.int32:
offset = 0b10010010010010010010010010010010
elif cfg.pack_dtype == torch.int16:
offset = 0b1001001001001001
elif cfg.pack_dtype == torch.int8:
offset = 0b10010010

submodule.qzeros.data[:, range(1, submodule.qzeros.data.shape[1], 3)] += (
0b10010010010010010010010010010010
offset
)

# range 2 offset
if cfg.pack_dtype == torch.int64:
offset = 0b0100100100100100100100100100100101001001001001001001001001001001
elif cfg.pack_dtype == torch.int32:
offset = 0b01001001001001001001001001001001
elif cfg.pack_dtype == torch.int16:
offset = 0b0100100100100100
elif cfg.pack_dtype == torch.int8:
offset = 0b01001001

submodule.qzeros.data[:, range(2, submodule.qzeros.data.shape[1], 3)] += (
0b01001001001001001001001001001001
offset
)
elif cfg.bits == 4:
if cfg.pack_dtype == torch.int64:
Expand Down