Upload 17 files
Browse files- __init__.py +16 -1
- __main__.py +33 -4
- config.py +6 -0
- gguf.py +287 -36
- gui.py +167 -23
- q4_0.py +444 -0
__init__.py
CHANGED
|
@@ -21,9 +21,18 @@ from .factored import (
|
|
| 21 |
factor_only_solve,
|
| 22 |
factor_q2k_block,
|
| 23 |
)
|
| 24 |
-
from .gguf import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
from .pipeline import Q2KQuantizer, QuantizedTensor, TensorStats
|
| 26 |
from .q2k import Q2KBlock, QK_K, dequantize_params, pack_codes, unpack_codes
|
|
|
|
| 27 |
|
| 28 |
__all__ = [
|
| 29 |
"HPCConfig",
|
|
@@ -47,8 +56,14 @@ __all__ = [
|
|
| 47 |
"factor_q2k_block",
|
| 48 |
"GGUFReader",
|
| 49 |
"expand_importance",
|
|
|
|
|
|
|
| 50 |
"lookup_imatrix",
|
| 51 |
"read_imatrix",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
"pack_codes",
|
| 53 |
"unpack_codes",
|
| 54 |
]
|
|
|
|
| 21 |
factor_only_solve,
|
| 22 |
factor_q2k_block,
|
| 23 |
)
|
| 24 |
+
from .gguf import (
|
| 25 |
+
GGUFReader,
|
| 26 |
+
expand_importance,
|
| 27 |
+
is_q2k_eligible,
|
| 28 |
+
is_q4_0_eligible,
|
| 29 |
+
lookup_imatrix,
|
| 30 |
+
read_imatrix,
|
| 31 |
+
target_quant_type,
|
| 32 |
+
)
|
| 33 |
from .pipeline import Q2KQuantizer, QuantizedTensor, TensorStats
|
| 34 |
from .q2k import Q2KBlock, QK_K, dequantize_params, pack_codes, unpack_codes
|
| 35 |
+
from .q4_0 import QK4_0, dequantize_q4_0_bytes, quantize_tensor_q4_0
|
| 36 |
|
| 37 |
__all__ = [
|
| 38 |
"HPCConfig",
|
|
|
|
| 56 |
"factor_q2k_block",
|
| 57 |
"GGUFReader",
|
| 58 |
"expand_importance",
|
| 59 |
+
"is_q2k_eligible",
|
| 60 |
+
"is_q4_0_eligible",
|
| 61 |
"lookup_imatrix",
|
| 62 |
"read_imatrix",
|
| 63 |
+
"target_quant_type",
|
| 64 |
+
"QK4_0",
|
| 65 |
+
"dequantize_q4_0_bytes",
|
| 66 |
+
"quantize_tensor_q4_0",
|
| 67 |
"pack_codes",
|
| 68 |
"unpack_codes",
|
| 69 |
]
|
__main__.py
CHANGED
|
@@ -26,6 +26,7 @@ from .gguf import (
|
|
| 26 |
is_q2k_eligible,
|
| 27 |
lookup_imatrix,
|
| 28 |
read_imatrix,
|
|
|
|
| 29 |
write_quantized_gguf,
|
| 30 |
)
|
| 31 |
from .pipeline import Q2KQuantizer
|
|
@@ -46,6 +47,16 @@ def _config_from_args(args) -> HPCConfig:
|
|
| 46 |
cfg.optimizer = "mse"
|
| 47 |
if args.no_spectral:
|
| 48 |
cfg.use_spectral = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
return cfg.validate()
|
| 50 |
|
| 51 |
|
|
@@ -82,9 +93,18 @@ def _run_gguf(args, cfg: HPCConfig) -> None:
|
|
| 82 |
if args.list_tensors or (not args.tensor and not args.all_q2k):
|
| 83 |
print(f"{reader.path}: {len(reader.tensors)} tensors, {len(reader.metadata)} metadata keys")
|
| 84 |
for ti in reader.tensors:
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
print(
|
| 87 |
-
f" {tag} {ti.name:48s} {ti.type_name:6s} "
|
| 88 |
f"dims={ti.dims} row={ti.row_width}"
|
| 89 |
)
|
| 90 |
return
|
|
@@ -108,8 +128,8 @@ def _run_gguf(args, cfg: HPCConfig) -> None:
|
|
| 108 |
verbose=True,
|
| 109 |
)
|
| 110 |
print(
|
| 111 |
-
f"wrote {args.output}: {int(stats
|
| 112 |
-
f"rmse={stats['rmse']:.6e}"
|
| 113 |
)
|
| 114 |
return
|
| 115 |
|
|
@@ -231,6 +251,15 @@ def main() -> None:
|
|
| 231 |
parser.add_argument("--device", default=None, help="compute device: auto (default), cuda, or cpu")
|
| 232 |
parser.add_argument("--mse", action="store_true", help="disable HPC sequence search")
|
| 233 |
parser.add_argument("--no-spectral", action="store_true", help="disable spectral/DC objective")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
parser.add_argument("--verbose", action="store_true")
|
| 235 |
parser.add_argument("--bench", action="store_true", help="measure solver gains vs C port")
|
| 236 |
parser.add_argument("--bench-per-kind", type=int, default=12)
|
|
|
|
| 26 |
is_q2k_eligible,
|
| 27 |
lookup_imatrix,
|
| 28 |
read_imatrix,
|
| 29 |
+
target_quant_type,
|
| 30 |
write_quantized_gguf,
|
| 31 |
)
|
| 32 |
from .pipeline import Q2KQuantizer
|
|
|
|
| 47 |
cfg.optimizer = "mse"
|
| 48 |
if args.no_spectral:
|
| 49 |
cfg.use_spectral = False
|
| 50 |
+
if args.no_q4_fallback:
|
| 51 |
+
cfg.enable_q4_fallback = False
|
| 52 |
+
if args.keep_embd:
|
| 53 |
+
cfg.quantize_embd_q4 = False
|
| 54 |
+
if args.promote_attn_q4:
|
| 55 |
+
cfg.promote_attn_q4 = True
|
| 56 |
+
if args.format is not None:
|
| 57 |
+
cfg.quant_format = args.format
|
| 58 |
+
if args.format == "q2_k":
|
| 59 |
+
cfg.enable_q4_fallback = False
|
| 60 |
return cfg.validate()
|
| 61 |
|
| 62 |
|
|
|
|
| 93 |
if args.list_tensors or (not args.tensor and not args.all_q2k):
|
| 94 |
print(f"{reader.path}: {len(reader.tensors)} tensors, {len(reader.metadata)} metadata keys")
|
| 95 |
for ti in reader.tensors:
|
| 96 |
+
tgt = target_quant_type(
|
| 97 |
+
ti.name,
|
| 98 |
+
ti.dims,
|
| 99 |
+
enable_q4_fallback=cfg.enable_q4_fallback,
|
| 100 |
+
quantize_embd_q4=cfg.quantize_embd_q4,
|
| 101 |
+
promote_attn_q4=cfg.promote_attn_q4,
|
| 102 |
+
quant_format=cfg.quant_format,
|
| 103 |
+
source_type=ti.type,
|
| 104 |
+
)
|
| 105 |
+
tag = tgt if tgt else "COPY"
|
| 106 |
print(
|
| 107 |
+
f" {tag:4s} {ti.name:48s} {ti.type_name:6s} "
|
| 108 |
f"dims={ti.dims} row={ti.row_width}"
|
| 109 |
)
|
| 110 |
return
|
|
|
|
| 128 |
verbose=True,
|
| 129 |
)
|
| 130 |
print(
|
| 131 |
+
f"wrote {args.output}: {int(stats.get('q2_k', 0))} Q2_K + {int(stats.get('q4_0', 0))} Q4_0 "
|
| 132 |
+
f"({int(stats['quantized'])}/{int(stats['tensors'])} tensors), rmse={stats['rmse']:.6e}"
|
| 133 |
)
|
| 134 |
return
|
| 135 |
|
|
|
|
| 251 |
parser.add_argument("--device", default=None, help="compute device: auto (default), cuda, or cpu")
|
| 252 |
parser.add_argument("--mse", action="store_true", help="disable HPC sequence search")
|
| 253 |
parser.add_argument("--no-spectral", action="store_true", help="disable spectral/DC objective")
|
| 254 |
+
parser.add_argument(
|
| 255 |
+
"--format",
|
| 256 |
+
choices=("mixed", "q4_0", "q2_k"),
|
| 257 |
+
default=None,
|
| 258 |
+
help="quantization format mode: mixed (Q2_K if eligible else Q4_0), q4_0 (pure Q4_0), or q2_k (pure Q2_K)",
|
| 259 |
+
)
|
| 260 |
+
parser.add_argument("--no-q4-fallback", action="store_true", help="disable Q4_0 fallback for non-256-aligned tensors")
|
| 261 |
+
parser.add_argument("--keep-embd", action="store_true", help="keep token_embd/output.weight at source precision")
|
| 262 |
+
parser.add_argument("--promote-attn-q4", action="store_true", help="promote attention Q/K/V/O projections to Q4_0")
|
| 263 |
parser.add_argument("--verbose", action="store_true")
|
| 264 |
parser.add_argument("--bench", action="store_true", help="measure solver gains vs C port")
|
| 265 |
parser.add_argument("--bench-per-kind", type=int, default=12)
|
config.py
CHANGED
|
@@ -68,6 +68,10 @@ class HPCConfig:
|
|
| 68 |
use_factor_floor: bool = True
|
| 69 |
use_candidate_floor: bool = True
|
| 70 |
apply_dc_carry: bool = True
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
# ---- seed clamp -----------------------------------------------------
|
| 73 |
clamp_kurtosis_off: float = 6.0
|
|
@@ -116,4 +120,6 @@ class HPCConfig:
|
|
| 116 |
raise ValueError("workers must be >= 0 (0 = auto CPU count)")
|
| 117 |
if self.device not in ("auto", "cuda", "cpu") and not self.device.startswith("cuda:"):
|
| 118 |
raise ValueError("device must be 'auto', 'cuda', 'cuda:N', or 'cpu'")
|
|
|
|
|
|
|
| 119 |
return self
|
|
|
|
| 68 |
use_factor_floor: bool = True
|
| 69 |
use_candidate_floor: bool = True
|
| 70 |
apply_dc_carry: bool = True
|
| 71 |
+
quant_format: str = "mixed"
|
| 72 |
+
enable_q4_fallback: bool = True
|
| 73 |
+
quantize_embd_q4: bool = True
|
| 74 |
+
promote_attn_q4: bool = False
|
| 75 |
|
| 76 |
# ---- seed clamp -----------------------------------------------------
|
| 77 |
clamp_kurtosis_off: float = 6.0
|
|
|
|
| 120 |
raise ValueError("workers must be >= 0 (0 = auto CPU count)")
|
| 121 |
if self.device not in ("auto", "cuda", "cpu") and not self.device.startswith("cuda:"):
|
| 122 |
raise ValueError("device must be 'auto', 'cuda', 'cuda:N', or 'cpu'")
|
| 123 |
+
if self.quant_format not in ("mixed", "q4_0", "q2_k"):
|
| 124 |
+
raise ValueError("quant_format must be 'mixed', 'q4_0', or 'q2_k'")
|
| 125 |
return self
|
gguf.py
CHANGED
|
@@ -22,6 +22,7 @@ from pathlib import Path
|
|
| 22 |
import numpy as np
|
| 23 |
|
| 24 |
from .q2k import QK_K, blocks_to_bytes, dequantize_params_batch, unpack_codes
|
|
|
|
| 25 |
|
| 26 |
GGUF_MAGIC = 0x46554747
|
| 27 |
DEFAULT_ALIGNMENT = 32
|
|
@@ -70,6 +71,38 @@ BLOCK_BYTES = {
|
|
| 70 |
GGML_TYPE_Q8_0: 34,
|
| 71 |
GGML_TYPE_Q2_K: 84,
|
| 72 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
SUPPORTED_READ_TYPES = {
|
| 74 |
GGML_TYPE_F32,
|
| 75 |
GGML_TYPE_F16,
|
|
@@ -229,6 +262,30 @@ class GGUFReader:
|
|
| 229 |
raw = self.read_tensor_raw(name)
|
| 230 |
return _dequantize(raw, self.info(name)), self.info(name).row_width
|
| 231 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
|
| 233 |
def _dequantize(raw: bytes, ti: TensorInfo) -> np.ndarray:
|
| 234 |
t = ti.type
|
|
@@ -343,24 +400,36 @@ def expand_importance(
|
|
| 343 |
)
|
| 344 |
|
| 345 |
|
| 346 |
-
def
|
| 347 |
if len(dims) < 2:
|
| 348 |
-
return
|
| 349 |
-
if dims[0] % QK_K != 0:
|
| 350 |
-
return False
|
| 351 |
-
if "token_embd" in name or name == "output.weight":
|
| 352 |
-
return False
|
| 353 |
if "norm" in name or ".bias" in name:
|
| 354 |
-
return
|
| 355 |
if "ffn_gate_inp" in name:
|
| 356 |
-
return
|
| 357 |
if name.startswith("mm.") or name.startswith("a.") or name.startswith("v."):
|
| 358 |
-
return
|
| 359 |
if "altup" in name or "laurel" in name or "layer_output_scale" in name:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 360 |
return False
|
| 361 |
-
if
|
| 362 |
return False
|
| 363 |
-
if
|
| 364 |
return False
|
| 365 |
n_elements = 1
|
| 366 |
for d in dims:
|
|
@@ -368,6 +437,79 @@ def is_q2k_eligible(name: str, dims: tuple[int, ...]) -> bool:
|
|
| 368 |
return n_elements >= QK_K and n_elements % QK_K == 0
|
| 369 |
|
| 370 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 371 |
def _write_string(f, value: str) -> None:
|
| 372 |
data = value.encode("utf-8")
|
| 373 |
f.write(struct.pack("<Q", len(data)))
|
|
@@ -400,52 +542,83 @@ def write_quantized_gguf(
|
|
| 400 |
if missing:
|
| 401 |
raise KeyError(f"tensors not found: {sorted(missing)}")
|
| 402 |
|
| 403 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 404 |
quantized_count = 0
|
| 405 |
for ti in reader.tensors:
|
|
|
|
| 406 |
if names is not None:
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 412 |
)
|
| 413 |
-
|
| 414 |
-
want = quantize_all and is_q2k_eligible(ti.name, ti.dims)
|
| 415 |
-
compatible = True
|
| 416 |
-
if want and ti.type not in SUPPORTED_READ_TYPES:
|
| 417 |
if verbose:
|
| 418 |
print(f" copy (unsupported source {ti.type_name}): {ti.name}")
|
| 419 |
-
|
| 420 |
-
if
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
want = False
|
| 424 |
-
if want and limit and quantized_count >= limit:
|
| 425 |
-
want = False
|
| 426 |
-
if want:
|
| 427 |
quantized_count += 1
|
| 428 |
-
plan.append(
|
| 429 |
|
| 430 |
out_infos = []
|
| 431 |
data_offset = 0
|
| 432 |
total_planned_blocks = 0
|
| 433 |
-
for ti,
|
| 434 |
-
if
|
| 435 |
n_blocks = ti.n_elements // QK_K
|
| 436 |
out_type = GGML_TYPE_Q2_K
|
| 437 |
out_size = n_blocks * 84
|
| 438 |
total_planned_blocks += n_blocks
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 439 |
else:
|
| 440 |
out_type = ti.type
|
| 441 |
out_size = ti.n_bytes
|
| 442 |
out_infos.append((ti, out_type, out_size, data_offset))
|
| 443 |
data_offset = _align(data_offset + out_size, alignment)
|
| 444 |
|
|
|
|
|
|
|
| 445 |
kv_pairs = []
|
| 446 |
for key, vtype, raw in reader.kv_pairs:
|
| 447 |
if quantized_count and key == "general.file_type" and vtype == 4:
|
| 448 |
-
raw = struct.pack("<I",
|
| 449 |
elif quantized_count and key == "general.quantization_version" and vtype == 4:
|
| 450 |
raw = struct.pack("<I", 2)
|
| 451 |
kv_pairs.append((key, vtype, raw))
|
|
@@ -454,6 +627,8 @@ def write_quantized_gguf(
|
|
| 454 |
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 455 |
total_rmse = 0.0
|
| 456 |
total_quantized = 0
|
|
|
|
|
|
|
| 457 |
total_elements = 0
|
| 458 |
completed_planned_blocks = 0
|
| 459 |
model_t0 = time.time()
|
|
@@ -480,7 +655,8 @@ def write_quantized_gguf(
|
|
| 480 |
target = data_start + offset
|
| 481 |
if target > fout.tell():
|
| 482 |
fout.write(b"\x00" * (target - fout.tell()))
|
| 483 |
-
|
|
|
|
| 484 |
t_blocks = ti.n_elements // QK_K
|
| 485 |
has_imat = imat is not None and lookup_imatrix(imat, ti.name) is not None
|
| 486 |
|
|
@@ -490,11 +666,11 @@ def write_quantized_gguf(
|
|
| 490 |
phase_name = ev.get("phase", "")
|
| 491 |
done_b = int(ev.get("done", 0))
|
| 492 |
tot_b = max(int(ev.get("total", _tb)), 1)
|
| 493 |
-
if phase_name.startswith("Phase 2b"):
|
| 494 |
frac = 0.80 * (done_b / tot_b)
|
| 495 |
elif phase_name.startswith("Phase 3"):
|
| 496 |
frac = 0.82
|
| 497 |
-
elif phase_name.startswith("Phase 4
|
| 498 |
frac = 0.82 + 0.17 * (done_b / tot_b)
|
| 499 |
elif phase_name.startswith("Phase 4.8") or phase_name.startswith("Phase 5"):
|
| 500 |
frac = 1.0
|
|
@@ -548,6 +724,7 @@ def write_quantized_gguf(
|
|
| 548 |
total_rmse += res.stats.rmse * res.stats.rmse * x.size
|
| 549 |
total_elements += x.size
|
| 550 |
total_quantized += 1
|
|
|
|
| 551 |
if verbose:
|
| 552 |
print(
|
| 553 |
f" Q2_K {ti.name:48s} row={row:6d} "
|
|
@@ -562,6 +739,78 @@ def write_quantized_gguf(
|
|
| 562 |
float(res.stats.rmse),
|
| 563 |
imp is not None,
|
| 564 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 565 |
else:
|
| 566 |
if stage_callback is not None:
|
| 567 |
stage_callback(
|
|
@@ -585,6 +834,8 @@ def write_quantized_gguf(
|
|
| 585 |
return {
|
| 586 |
"tensors": float(len(out_infos)),
|
| 587 |
"quantized": float(total_quantized),
|
|
|
|
|
|
|
| 588 |
"elements": float(total_elements),
|
| 589 |
"rmse": rmse,
|
| 590 |
}
|
|
|
|
| 22 |
import numpy as np
|
| 23 |
|
| 24 |
from .q2k import QK_K, blocks_to_bytes, dequantize_params_batch, unpack_codes
|
| 25 |
+
from .q4_0 import Q4_0_BLOCK_BYTES, QK4_0, quantize_tensor_q4_0
|
| 26 |
|
| 27 |
GGUF_MAGIC = 0x46554747
|
| 28 |
DEFAULT_ALIGNMENT = 32
|
|
|
|
| 71 |
GGML_TYPE_Q8_0: 34,
|
| 72 |
GGML_TYPE_Q2_K: 84,
|
| 73 |
}
|
| 74 |
+
TYPE_BPW = {
|
| 75 |
+
GGML_TYPE_F32: 32.0,
|
| 76 |
+
GGML_TYPE_F16: 16.0,
|
| 77 |
+
GGML_TYPE_BF16: 16.0,
|
| 78 |
+
GGML_TYPE_Q8_0: 8.5,
|
| 79 |
+
GGML_TYPE_Q5_1: 6.0,
|
| 80 |
+
GGML_TYPE_Q5_0: 5.5,
|
| 81 |
+
GGML_TYPE_Q4_1: 5.0,
|
| 82 |
+
GGML_TYPE_Q4_0: 4.5,
|
| 83 |
+
GGML_TYPE_Q2_K: 2.625,
|
| 84 |
+
11: 3.4375, # Q3_K
|
| 85 |
+
12: 4.5, # Q4_K
|
| 86 |
+
13: 5.5, # Q5_K
|
| 87 |
+
14: 6.5625, # Q6_K
|
| 88 |
+
15: 8.5, # Q8_K
|
| 89 |
+
16: 2.0625, # IQ2_XXS
|
| 90 |
+
17: 2.3125, # IQ2_XS
|
| 91 |
+
18: 3.0625, # IQ3_XXS
|
| 92 |
+
19: 1.5625, # IQ1_S
|
| 93 |
+
20: 4.5, # IQ4_NL
|
| 94 |
+
21: 3.4375, # IQ3_S
|
| 95 |
+
22: 2.5625, # IQ2_S
|
| 96 |
+
23: 4.25, # IQ4_XS
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def source_type_bpw(ttype: int) -> float:
|
| 101 |
+
if ttype in TYPE_BPW:
|
| 102 |
+
return TYPE_BPW[ttype]
|
| 103 |
+
if ttype in BLOCK_SIZE and ttype in BLOCK_BYTES:
|
| 104 |
+
return (BLOCK_BYTES[ttype] * 8.0) / BLOCK_SIZE[ttype]
|
| 105 |
+
return 16.0
|
| 106 |
SUPPORTED_READ_TYPES = {
|
| 107 |
GGML_TYPE_F32,
|
| 108 |
GGML_TYPE_F16,
|
|
|
|
| 262 |
raw = self.read_tensor_raw(name)
|
| 263 |
return _dequantize(raw, self.info(name)), self.info(name).row_width
|
| 264 |
|
| 265 |
+
def iter_tensor_row_chunks(self, name: str, max_elements: int = 8_388_608):
|
| 266 |
+
"""Stream a tensor in row-aligned float32 chunks to bound peak RAM."""
|
| 267 |
+
ti = self.info(name)
|
| 268 |
+
row = ti.row_width
|
| 269 |
+
blk = BLOCK_SIZE[ti.type]
|
| 270 |
+
if row <= 0 or row % blk != 0 or ti.n_elements % row != 0:
|
| 271 |
+
x, r = self.read_tensor(name)
|
| 272 |
+
yield x, r, 0, ti.n_elements // max(r, 1)
|
| 273 |
+
return
|
| 274 |
+
n_rows = ti.n_elements // row
|
| 275 |
+
rows_per_chunk = max(1, max_elements // row)
|
| 276 |
+
bytes_per_row = (row // blk) * BLOCK_BYTES[ti.type]
|
| 277 |
+
with self.path.open("rb") as f:
|
| 278 |
+
for r0 in range(0, n_rows, rows_per_chunk):
|
| 279 |
+
r1 = min(r0 + rows_per_chunk, n_rows)
|
| 280 |
+
chunk_elems = (r1 - r0) * row
|
| 281 |
+
chunk_bytes = (r1 - r0) * bytes_per_row
|
| 282 |
+
f.seek(self.data_start + ti.offset + r0 * bytes_per_row)
|
| 283 |
+
raw = f.read(chunk_bytes)
|
| 284 |
+
if len(raw) != chunk_bytes:
|
| 285 |
+
raise ValueError(f"{name}: truncated tensor data")
|
| 286 |
+
sub_ti = TensorInfo(ti.name, (chunk_elems,), ti.type, 0)
|
| 287 |
+
yield _dequantize(raw, sub_ti), row, r0, r1
|
| 288 |
+
|
| 289 |
|
| 290 |
def _dequantize(raw: bytes, ti: TensorInfo) -> np.ndarray:
|
| 291 |
t = ti.type
|
|
|
|
| 400 |
)
|
| 401 |
|
| 402 |
|
| 403 |
+
def _is_skipped_metadata_tensor(name: str, dims: tuple[int, ...]) -> bool:
|
| 404 |
if len(dims) < 2:
|
| 405 |
+
return True
|
|
|
|
|
|
|
|
|
|
|
|
|
| 406 |
if "norm" in name or ".bias" in name:
|
| 407 |
+
return True
|
| 408 |
if "ffn_gate_inp" in name:
|
| 409 |
+
return True
|
| 410 |
if name.startswith("mm.") or name.startswith("a.") or name.startswith("v."):
|
| 411 |
+
return True
|
| 412 |
if "altup" in name or "laurel" in name or "layer_output_scale" in name:
|
| 413 |
+
return True
|
| 414 |
+
if "ssm_a" in name.split(".") or "A_log" in name:
|
| 415 |
+
return True
|
| 416 |
+
if "ssm_dt" in name or "dt_bias" in name:
|
| 417 |
+
return True
|
| 418 |
+
if "ssm_conv1d" in name or "conv1d.weight" in name:
|
| 419 |
+
return True
|
| 420 |
+
return False
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def _is_embd_or_head(name: str) -> bool:
|
| 424 |
+
return "token_embd" in name or name == "output.weight" or name.endswith(".output.weight")
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def is_q2k_eligible(name: str, dims: tuple[int, ...]) -> bool:
|
| 428 |
+
if _is_skipped_metadata_tensor(name, dims):
|
| 429 |
return False
|
| 430 |
+
if _is_embd_or_head(name):
|
| 431 |
return False
|
| 432 |
+
if dims[0] % QK_K != 0:
|
| 433 |
return False
|
| 434 |
n_elements = 1
|
| 435 |
for d in dims:
|
|
|
|
| 437 |
return n_elements >= QK_K and n_elements % QK_K == 0
|
| 438 |
|
| 439 |
|
| 440 |
+
def is_q4_0_eligible(
|
| 441 |
+
name: str,
|
| 442 |
+
dims: tuple[int, ...],
|
| 443 |
+
include_embd: bool = True,
|
| 444 |
+
promote_attn: bool = False,
|
| 445 |
+
allow_q2k_tensors: bool = False,
|
| 446 |
+
) -> bool:
|
| 447 |
+
"""True for 32-aligned 2D/3D weight tensors eligible for Q4_0."""
|
| 448 |
+
if _is_skipped_metadata_tensor(name, dims):
|
| 449 |
+
return False
|
| 450 |
+
is_embd = _is_embd_or_head(name)
|
| 451 |
+
if is_embd and not include_embd:
|
| 452 |
+
return False
|
| 453 |
+
if not allow_q2k_tensors and not is_embd and not (promote_attn and _is_attention_projection(name)):
|
| 454 |
+
if is_q2k_eligible(name, dims):
|
| 455 |
+
return False
|
| 456 |
+
if dims[0] % QK4_0 != 0:
|
| 457 |
+
return False
|
| 458 |
+
n_elements = 1
|
| 459 |
+
for d in dims:
|
| 460 |
+
n_elements *= int(d)
|
| 461 |
+
return n_elements >= QK4_0 and n_elements % QK4_0 == 0
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def target_quant_type(
|
| 465 |
+
name: str,
|
| 466 |
+
dims: tuple[int, ...],
|
| 467 |
+
enable_q4_fallback: bool = True,
|
| 468 |
+
quantize_embd_q4: bool = True,
|
| 469 |
+
promote_attn_q4: bool = False,
|
| 470 |
+
quant_format: str = "mixed",
|
| 471 |
+
source_type: int | None = None,
|
| 472 |
+
) -> str | None:
|
| 473 |
+
"""Determine target quantization format ('Q2_K', 'Q4_0', or None for Copy).
|
| 474 |
+
|
| 475 |
+
Modes:
|
| 476 |
+
* 'mixed' (default): all Q2_K-eligible tensors -> Q2_K; non-Q2_K 32-aligned
|
| 477 |
+
tensors (and embeddings/head if quantize_embd_q4) -> Q4_0.
|
| 478 |
+
* 'q4_0': all 32-aligned eligible weight tensors -> Q4_0.
|
| 479 |
+
* 'q2_k': only Q2_K-eligible tensors -> Q2_K; everything else copied.
|
| 480 |
+
|
| 481 |
+
Never promotes a lower-bit source tensor to a higher-bit target format
|
| 482 |
+
(e.g., a Q2_K source tensor is never re-quantized to Q4_0).
|
| 483 |
+
"""
|
| 484 |
+
tgt: str | None = None
|
| 485 |
+
if quant_format == "q4_0":
|
| 486 |
+
if is_q4_0_eligible(
|
| 487 |
+
name, dims, include_embd=quantize_embd_q4, allow_q2k_tensors=True
|
| 488 |
+
):
|
| 489 |
+
tgt = "Q4_0"
|
| 490 |
+
elif quant_format == "q2_k":
|
| 491 |
+
if is_q2k_eligible(name, dims):
|
| 492 |
+
tgt = "Q2_K"
|
| 493 |
+
else:
|
| 494 |
+
if promote_attn_q4 and _is_attention_projection(name) and is_q4_0_eligible(
|
| 495 |
+
name, dims, include_embd=quantize_embd_q4, promote_attn=True
|
| 496 |
+
):
|
| 497 |
+
tgt = "Q4_0"
|
| 498 |
+
elif is_q2k_eligible(name, dims):
|
| 499 |
+
tgt = "Q2_K"
|
| 500 |
+
elif enable_q4_fallback and is_q4_0_eligible(
|
| 501 |
+
name, dims, include_embd=quantize_embd_q4, promote_attn=False
|
| 502 |
+
):
|
| 503 |
+
tgt = "Q4_0"
|
| 504 |
+
|
| 505 |
+
if tgt is not None and source_type is not None:
|
| 506 |
+
src_bpw = source_type_bpw(int(source_type))
|
| 507 |
+
tgt_bpw = 2.625 if tgt == "Q2_K" else 4.5
|
| 508 |
+
if src_bpw <= tgt_bpw + 1.0e-6:
|
| 509 |
+
return None
|
| 510 |
+
return tgt
|
| 511 |
+
|
| 512 |
+
|
| 513 |
def _write_string(f, value: str) -> None:
|
| 514 |
data = value.encode("utf-8")
|
| 515 |
f.write(struct.pack("<Q", len(data)))
|
|
|
|
| 542 |
if missing:
|
| 543 |
raise KeyError(f"tensors not found: {sorted(missing)}")
|
| 544 |
|
| 545 |
+
cfg = getattr(quantizer, "config", None)
|
| 546 |
+
enable_q4 = bool(getattr(cfg, "enable_q4_fallback", True))
|
| 547 |
+
embd_q4 = bool(getattr(cfg, "quantize_embd_q4", True))
|
| 548 |
+
attn_q4 = bool(getattr(cfg, "promote_attn_q4", False))
|
| 549 |
+
q_format = str(getattr(cfg, "quant_format", "mixed"))
|
| 550 |
+
|
| 551 |
+
plan: list[str | None] = []
|
| 552 |
quantized_count = 0
|
| 553 |
for ti in reader.tensors:
|
| 554 |
+
target_fmt: str | None = None
|
| 555 |
if names is not None:
|
| 556 |
+
if ti.name in names:
|
| 557 |
+
target_fmt = target_quant_type(
|
| 558 |
+
ti.name,
|
| 559 |
+
ti.dims,
|
| 560 |
+
enable_q4_fallback=enable_q4,
|
| 561 |
+
quantize_embd_q4=embd_q4,
|
| 562 |
+
promote_attn_q4=attn_q4,
|
| 563 |
+
quant_format=q_format,
|
| 564 |
+
source_type=ti.type,
|
| 565 |
+
)
|
| 566 |
+
if target_fmt is None:
|
| 567 |
+
src_bpw = source_type_bpw(ti.type)
|
| 568 |
+
if q_format == "q4_0" and len(ti.dims) >= 2 and ti.dims[0] % QK4_0 == 0 and src_bpw > 4.5:
|
| 569 |
+
target_fmt = "Q4_0"
|
| 570 |
+
elif len(ti.dims) >= 2 and ti.dims[0] % QK_K == 0 and ti.n_elements % QK_K == 0 and src_bpw > 2.625:
|
| 571 |
+
target_fmt = "Q2_K"
|
| 572 |
+
elif len(ti.dims) >= 2 and ti.dims[0] % QK4_0 == 0 and ti.n_elements % QK4_0 == 0 and src_bpw > 4.5:
|
| 573 |
+
target_fmt = "Q4_0"
|
| 574 |
+
elif verbose:
|
| 575 |
+
print(f" copy (already <= target precision or unaligned): {ti.name}")
|
| 576 |
+
elif quantize_all:
|
| 577 |
+
target_fmt = target_quant_type(
|
| 578 |
+
ti.name,
|
| 579 |
+
ti.dims,
|
| 580 |
+
enable_q4_fallback=enable_q4,
|
| 581 |
+
quantize_embd_q4=embd_q4,
|
| 582 |
+
promote_attn_q4=attn_q4,
|
| 583 |
+
quant_format=q_format,
|
| 584 |
+
source_type=ti.type,
|
| 585 |
)
|
| 586 |
+
if target_fmt and ti.type not in SUPPORTED_READ_TYPES:
|
|
|
|
|
|
|
|
|
|
| 587 |
if verbose:
|
| 588 |
print(f" copy (unsupported source {ti.type_name}): {ti.name}")
|
| 589 |
+
target_fmt = None
|
| 590 |
+
if target_fmt and limit and quantized_count >= limit:
|
| 591 |
+
target_fmt = None
|
| 592 |
+
if target_fmt:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 593 |
quantized_count += 1
|
| 594 |
+
plan.append(target_fmt)
|
| 595 |
|
| 596 |
out_infos = []
|
| 597 |
data_offset = 0
|
| 598 |
total_planned_blocks = 0
|
| 599 |
+
for ti, fmt in zip(reader.tensors, plan):
|
| 600 |
+
if fmt == "Q2_K":
|
| 601 |
n_blocks = ti.n_elements // QK_K
|
| 602 |
out_type = GGML_TYPE_Q2_K
|
| 603 |
out_size = n_blocks * 84
|
| 604 |
total_planned_blocks += n_blocks
|
| 605 |
+
elif fmt == "Q4_0":
|
| 606 |
+
n_blocks = ti.n_elements // QK4_0
|
| 607 |
+
out_type = GGML_TYPE_Q4_0
|
| 608 |
+
out_size = n_blocks * Q4_0_BLOCK_BYTES
|
| 609 |
+
total_planned_blocks += max(1, n_blocks // 8)
|
| 610 |
else:
|
| 611 |
out_type = ti.type
|
| 612 |
out_size = ti.n_bytes
|
| 613 |
out_infos.append((ti, out_type, out_size, data_offset))
|
| 614 |
data_offset = _align(data_offset + out_size, alignment)
|
| 615 |
|
| 616 |
+
has_q2k = any(fmt == "Q2_K" for fmt in plan)
|
| 617 |
+
ftype_code = 10 if has_q2k else 2 # 10 = MOSTLY_Q2_K, 2 = MOSTLY_Q4_0
|
| 618 |
kv_pairs = []
|
| 619 |
for key, vtype, raw in reader.kv_pairs:
|
| 620 |
if quantized_count and key == "general.file_type" and vtype == 4:
|
| 621 |
+
raw = struct.pack("<I", ftype_code)
|
| 622 |
elif quantized_count and key == "general.quantization_version" and vtype == 4:
|
| 623 |
raw = struct.pack("<I", 2)
|
| 624 |
kv_pairs.append((key, vtype, raw))
|
|
|
|
| 627 |
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 628 |
total_rmse = 0.0
|
| 629 |
total_quantized = 0
|
| 630 |
+
total_q2k = 0
|
| 631 |
+
total_q4_0 = 0
|
| 632 |
total_elements = 0
|
| 633 |
completed_planned_blocks = 0
|
| 634 |
model_t0 = time.time()
|
|
|
|
| 655 |
target = data_start + offset
|
| 656 |
if target > fout.tell():
|
| 657 |
fout.write(b"\x00" * (target - fout.tell()))
|
| 658 |
+
fmt = plan[idx]
|
| 659 |
+
if fmt == "Q2_K":
|
| 660 |
t_blocks = ti.n_elements // QK_K
|
| 661 |
has_imat = imat is not None and lookup_imatrix(imat, ti.name) is not None
|
| 662 |
|
|
|
|
| 666 |
phase_name = ev.get("phase", "")
|
| 667 |
done_b = int(ev.get("done", 0))
|
| 668 |
tot_b = max(int(ev.get("total", _tb)), 1)
|
| 669 |
+
if phase_name.startswith("Phase 2b") or "Phase 1–2b" in phase_name:
|
| 670 |
frac = 0.80 * (done_b / tot_b)
|
| 671 |
elif phase_name.startswith("Phase 3"):
|
| 672 |
frac = 0.82
|
| 673 |
+
elif "Phase 4" in phase_name and not phase_name.startswith("Phase 4.8"):
|
| 674 |
frac = 0.82 + 0.17 * (done_b / tot_b)
|
| 675 |
elif phase_name.startswith("Phase 4.8") or phase_name.startswith("Phase 5"):
|
| 676 |
frac = 1.0
|
|
|
|
| 724 |
total_rmse += res.stats.rmse * res.stats.rmse * x.size
|
| 725 |
total_elements += x.size
|
| 726 |
total_quantized += 1
|
| 727 |
+
total_q2k += 1
|
| 728 |
if verbose:
|
| 729 |
print(
|
| 730 |
f" Q2_K {ti.name:48s} row={row:6d} "
|
|
|
|
| 739 |
float(res.stats.rmse),
|
| 740 |
imp is not None,
|
| 741 |
)
|
| 742 |
+
elif fmt == "Q4_0":
|
| 743 |
+
t_blocks_q4 = ti.n_elements // QK4_0
|
| 744 |
+
eff_tb = max(1, t_blocks_q4 // 8)
|
| 745 |
+
raw_imp = lookup_imatrix(imat, ti.name) if imat is not None else None
|
| 746 |
+
has_imat = raw_imp is not None and raw_imp.size == ti.row_width
|
| 747 |
+
written_bytes = 0
|
| 748 |
+
sse_q4 = 0.0
|
| 749 |
+
done_q4_blks = 0
|
| 750 |
+
t_q4_start = time.time()
|
| 751 |
+
|
| 752 |
+
for x_chunk, row, _r0, _r1 in reader.iter_tensor_row_chunks(ti.name, max_elements=8_388_608):
|
| 753 |
+
if stop_event is not None and stop_event.is_set():
|
| 754 |
+
raise InterruptedError("Quantization cancelled by user")
|
| 755 |
+
imp_chunk = expand_importance(raw_imp, x_chunk.size, row) if has_imat else None
|
| 756 |
+
q4_bytes, nb_chunk, chunk_rmse = quantize_tensor_q4_0(
|
| 757 |
+
x_chunk, importance=imp_chunk, cfg=cfg
|
| 758 |
+
)
|
| 759 |
+
fout.write(q4_bytes)
|
| 760 |
+
written_bytes += len(q4_bytes)
|
| 761 |
+
sse_q4 += (chunk_rmse * chunk_rmse) * x_chunk.size
|
| 762 |
+
done_q4_blks += nb_chunk
|
| 763 |
+
if stage_callback is not None:
|
| 764 |
+
frac = done_q4_blks / max(t_blocks_q4, 1)
|
| 765 |
+
eff_blocks = completed_planned_blocks + frac * eff_tb
|
| 766 |
+
elapsed_model = max(time.time() - model_t0, 1.0e-6)
|
| 767 |
+
model_rate = eff_blocks / elapsed_model
|
| 768 |
+
model_eta = max(total_planned_blocks - eff_blocks, 0.0) / max(model_rate, 1.0e-6)
|
| 769 |
+
el_q4 = max(time.time() - t_q4_start, 1.0e-6)
|
| 770 |
+
r_q4 = done_q4_blks / el_q4
|
| 771 |
+
eta_q4 = (t_blocks_q4 - done_q4_blks) / max(r_q4, 1.0e-6)
|
| 772 |
+
stage_callback(
|
| 773 |
+
idx + 1,
|
| 774 |
+
len(out_infos),
|
| 775 |
+
ti,
|
| 776 |
+
{
|
| 777 |
+
"phase": "Q4_0: Analog + WLS + FP16-ULP Quantization",
|
| 778 |
+
"done": done_q4_blks,
|
| 779 |
+
"total": t_blocks_q4,
|
| 780 |
+
"detail": f"blk {done_q4_blks:,}/{t_blocks_q4:,} ({r_q4:.0f} blk/s) rmse={chunk_rmse:.6e}",
|
| 781 |
+
"rate": r_q4,
|
| 782 |
+
"eta": eta_q4,
|
| 783 |
+
"rmse": chunk_rmse,
|
| 784 |
+
"sigma": float(np.sqrt(np.mean(x_chunk.astype(np.float64) ** 2))),
|
| 785 |
+
"model_pct": 100.0 * eff_blocks / max(total_planned_blocks, 1),
|
| 786 |
+
"model_eta": model_eta,
|
| 787 |
+
"model_done_blocks": int(eff_blocks),
|
| 788 |
+
"model_total_blocks": total_planned_blocks,
|
| 789 |
+
},
|
| 790 |
+
)
|
| 791 |
+
|
| 792 |
+
if written_bytes != out_size:
|
| 793 |
+
raise RuntimeError(f"{ti.name}: Q4_0 payload size mismatch")
|
| 794 |
+
completed_planned_blocks += eff_tb
|
| 795 |
+
q4_rmse = float(np.sqrt(sse_q4 / ti.n_elements))
|
| 796 |
+
total_rmse += sse_q4
|
| 797 |
+
total_elements += ti.n_elements
|
| 798 |
+
total_quantized += 1
|
| 799 |
+
total_q4_0 += 1
|
| 800 |
+
if verbose:
|
| 801 |
+
print(
|
| 802 |
+
f" Q4_0 {ti.name:48s} row={ti.row_width:6d} "
|
| 803 |
+
f"rmse={q4_rmse:.6e} imatrix={'yes' if has_imat else 'no'}"
|
| 804 |
+
)
|
| 805 |
+
if progress_callback is not None:
|
| 806 |
+
progress_callback(
|
| 807 |
+
idx + 1,
|
| 808 |
+
len(out_infos),
|
| 809 |
+
ti.name,
|
| 810 |
+
"Q4_0",
|
| 811 |
+
q4_rmse,
|
| 812 |
+
has_imat,
|
| 813 |
+
)
|
| 814 |
else:
|
| 815 |
if stage_callback is not None:
|
| 816 |
stage_callback(
|
|
|
|
| 834 |
return {
|
| 835 |
"tensors": float(len(out_infos)),
|
| 836 |
"quantized": float(total_quantized),
|
| 837 |
+
"q2_k": float(total_q2k),
|
| 838 |
+
"q4_0": float(total_q4_0),
|
| 839 |
"elements": float(total_elements),
|
| 840 |
"rmse": rmse,
|
| 841 |
}
|
gui.py
CHANGED
|
@@ -41,7 +41,7 @@ from hpc_quantize_v2 import (
|
|
| 41 |
lookup_imatrix,
|
| 42 |
read_imatrix,
|
| 43 |
)
|
| 44 |
-
from hpc_quantize_v2.gguf import is_q2k_eligible, write_quantized_gguf
|
| 45 |
from hpc_quantize_v2.reference import reference_solve, synthetic_cases
|
| 46 |
|
| 47 |
|
|
@@ -110,6 +110,11 @@ class HPCQuantizeGUI:
|
|
| 110 |
self.factor_floor_var = tk.BooleanVar(value=True)
|
| 111 |
self.cand_floor_var = tk.BooleanVar(value=True)
|
| 112 |
self.dc_carry_var = tk.BooleanVar(value=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
self.dc_lambda_var = tk.DoubleVar(value=1.0)
|
| 115 |
self.vw_lambda_var = tk.DoubleVar(value=1.0)
|
|
@@ -143,6 +148,10 @@ class HPCQuantizeGUI:
|
|
| 143 |
self.workers_var,
|
| 144 |
self.device_var,
|
| 145 |
self.use_spectral_var,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
):
|
| 147 |
v.trace_add("write", lambda *_: self._update_cli_preview())
|
| 148 |
|
|
@@ -178,8 +187,48 @@ class HPCQuantizeGUI:
|
|
| 178 |
style.map("Treeview", background=[("selected", accent)])
|
| 179 |
|
| 180 |
def _build_layout(self) -> None:
|
| 181 |
-
|
| 182 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
|
| 184 |
# 1. File Selection Frame
|
| 185 |
files_frame = ttk.LabelFrame(main, text="1. GGUF & iMatrix Paths", padding=8)
|
|
@@ -217,12 +266,28 @@ class HPCQuantizeGUI:
|
|
| 217 |
mode_row.pack(fill=tk.X, pady=(0, 4))
|
| 218 |
ttk.Label(mode_row, text="Target Scope:").pack(side=tk.LEFT, padx=(0, 8))
|
| 219 |
ttk.Radiobutton(
|
| 220 |
-
mode_row, text="All
|
| 221 |
).pack(side=tk.LEFT, padx=4)
|
| 222 |
ttk.Radiobutton(
|
| 223 |
mode_row, text="Selected Tensor(s)", variable=self.mode_var, value="selected"
|
| 224 |
).pack(side=tk.LEFT, padx=4)
|
| 225 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
opt_row = ttk.Frame(opt_frame)
|
| 227 |
opt_row.pack(fill=tk.X, pady=(0, 4))
|
| 228 |
ttk.Label(opt_row, text="Global Optimizer:").pack(side=tk.LEFT, padx=(0, 8))
|
|
@@ -265,6 +330,24 @@ class HPCQuantizeGUI:
|
|
| 265 |
text="Local-Safety Candidate & Factored Floors (Monotone Bound)",
|
| 266 |
variable=self.factor_floor_var,
|
| 267 |
).pack(anchor=tk.W, pady=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
|
| 269 |
grid_f = ttk.Frame(opt_frame)
|
| 270 |
grid_f.pack(fill=tk.X, pady=4)
|
|
@@ -303,23 +386,34 @@ class HPCQuantizeGUI:
|
|
| 303 |
|
| 304 |
search_row = ttk.Frame(browser_frame)
|
| 305 |
search_row.pack(fill=tk.X, pady=(0, 6))
|
| 306 |
-
ttk.Label(search_row, text="Filter:").pack(side=tk.LEFT, padx=(0,
|
| 307 |
filter_entry = ttk.Entry(search_row, textvariable=self.filter_var)
|
| 308 |
filter_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
|
| 309 |
filter_entry.bind("<KeyRelease>", lambda _e: self._populate_tensor_tree())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 310 |
ttk.Button(
|
| 311 |
-
search_row, text="Select
|
| 312 |
).pack(side=tk.LEFT, padx=4)
|
| 313 |
|
| 314 |
cols = ("name", "type", "dims", "row", "q2k", "imat", "state")
|
| 315 |
self.tree = ttk.Treeview(browser_frame, columns=cols, show="headings", selectmode="extended")
|
| 316 |
self.tree.heading("name", text="Tensor Name")
|
| 317 |
-
self.tree.heading("type", text="
|
| 318 |
self.tree.heading("dims", text="Dims")
|
| 319 |
self.tree.heading("row", text="Row Width")
|
| 320 |
-
self.tree.heading("q2k", text="
|
| 321 |
self.tree.heading("imat", text="iMatrix")
|
| 322 |
self.tree.heading("state", text="Live Status / RMSE")
|
|
|
|
|
|
|
|
|
|
| 323 |
|
| 324 |
self.tree.column("name", width=220, anchor=tk.W)
|
| 325 |
self.tree.column("type", width=52, anchor=tk.CENTER)
|
|
@@ -497,6 +591,10 @@ class HPCQuantizeGUI:
|
|
| 497 |
vw_lambda=float(self.vw_lambda_var.get()),
|
| 498 |
dc_decay=float(self.dc_decay_var.get()),
|
| 499 |
sse_budget=float(self.sse_budget_var.get()),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 500 |
device=self.device_var.get(),
|
| 501 |
workers=int(self.workers_var.get()),
|
| 502 |
verbose=False,
|
|
@@ -521,6 +619,7 @@ class HPCQuantizeGUI:
|
|
| 521 |
cmd += ["--output", out]
|
| 522 |
if self.limit_var.get() > 0:
|
| 523 |
cmd += ["--limit", str(self.limit_var.get())]
|
|
|
|
| 524 |
cmd += ["--device", self.device_var.get()]
|
| 525 |
cmd += ["--workers", str(self.workers_var.get())]
|
| 526 |
cmd += ["--cand-d", str(self.cand_d_var.get()), "--cand-m", str(self.cand_m_var.get())]
|
|
@@ -528,6 +627,12 @@ class HPCQuantizeGUI:
|
|
| 528 |
cmd.append("--mse")
|
| 529 |
if not self.use_spectral_var.get():
|
| 530 |
cmd.append("--no-spectral")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 531 |
cmd.append("--verbose")
|
| 532 |
return " ".join(shlex.quote(part) for part in cmd)
|
| 533 |
|
|
@@ -560,12 +665,6 @@ class HPCQuantizeGUI:
|
|
| 560 |
return
|
| 561 |
try:
|
| 562 |
self._reader = GGUFReader(gguf_path)
|
| 563 |
-
eligible = sum(1 for t in self._reader.tensors if is_q2k_eligible(t.name, t.dims))
|
| 564 |
-
self._log(
|
| 565 |
-
f"Inspected {gguf_path}: {len(self._reader.tensors)} tensors "
|
| 566 |
-
f"({eligible} Q2_K-eligible), {len(self._reader.metadata)} metadata keys."
|
| 567 |
-
)
|
| 568 |
-
self.status_var.set(f"Loaded {len(self._reader.tensors)} tensors ({eligible} Q2_K-eligible).")
|
| 569 |
self._populate_tensor_tree()
|
| 570 |
except Exception as exc:
|
| 571 |
self._reader = None
|
|
@@ -576,28 +675,62 @@ class HPCQuantizeGUI:
|
|
| 576 |
if self._reader is None:
|
| 577 |
return
|
| 578 |
filt = self.filter_var.get().strip().lower()
|
|
|
|
|
|
|
| 579 |
for ti in self._reader.tensors:
|
| 580 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 581 |
continue
|
| 582 |
-
elig = is_q2k_eligible(ti.name, ti.dims)
|
| 583 |
has_imat = (
|
| 584 |
self._imatrix is not None
|
| 585 |
and lookup_imatrix(self._imatrix, ti.name) is not None
|
| 586 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 587 |
self.tree.insert(
|
| 588 |
"",
|
| 589 |
tk.END,
|
| 590 |
iid=ti.name,
|
|
|
|
| 591 |
values=(
|
| 592 |
ti.name,
|
| 593 |
ti.type_name,
|
| 594 |
str(ti.dims),
|
| 595 |
ti.row_width,
|
| 596 |
-
|
| 597 |
"Yes" if has_imat else "-",
|
| 598 |
-
|
| 599 |
),
|
| 600 |
)
|
|
|
|
|
|
|
|
|
|
| 601 |
|
| 602 |
def _select_all_eligible(self) -> None:
|
| 603 |
if self._reader is None:
|
|
@@ -605,7 +738,17 @@ class HPCQuantizeGUI:
|
|
| 605 |
eligible_ids = [
|
| 606 |
ti.name
|
| 607 |
for ti in self._reader.tensors
|
| 608 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 609 |
]
|
| 610 |
self.tree.selection_set(eligible_ids)
|
| 611 |
|
|
@@ -737,7 +880,8 @@ class HPCQuantizeGUI:
|
|
| 737 |
self._log_queue.put(
|
| 738 |
(
|
| 739 |
"done",
|
| 740 |
-
f"Wrote {out_path}: {int(stats
|
|
|
|
| 741 |
f"overall RMSE={stats['rmse']:.6e} ({dt_sec:.1f}s)",
|
| 742 |
)
|
| 743 |
)
|
|
@@ -880,10 +1024,10 @@ class HPCQuantizeGUI:
|
|
| 880 |
done, total, name, action, rmse, has_imat = payload # type: ignore[misc]
|
| 881 |
self.model_progress_var.set(100.0 * done / max(total, 1))
|
| 882 |
self.tensor_progress_var.set(100.0)
|
| 883 |
-
if action
|
| 884 |
-
self._update_tree_row_state(name, f"
|
| 885 |
self._log(
|
| 886 |
-
f"[{done}/{total}] FINISHED {name:42s} ->
|
| 887 |
)
|
| 888 |
else:
|
| 889 |
self._update_tree_row_state(name, "Copied verbatim")
|
|
|
|
| 41 |
lookup_imatrix,
|
| 42 |
read_imatrix,
|
| 43 |
)
|
| 44 |
+
from hpc_quantize_v2.gguf import is_q2k_eligible, target_quant_type, write_quantized_gguf
|
| 45 |
from hpc_quantize_v2.reference import reference_solve, synthetic_cases
|
| 46 |
|
| 47 |
|
|
|
|
| 110 |
self.factor_floor_var = tk.BooleanVar(value=True)
|
| 111 |
self.cand_floor_var = tk.BooleanVar(value=True)
|
| 112 |
self.dc_carry_var = tk.BooleanVar(value=True)
|
| 113 |
+
self.q4_fallback_var = tk.BooleanVar(value=True)
|
| 114 |
+
self.embd_q4_var = tk.BooleanVar(value=True)
|
| 115 |
+
self.promote_attn_q4_var = tk.BooleanVar(value=False)
|
| 116 |
+
self.quant_format_var = tk.StringVar(value="mixed")
|
| 117 |
+
self.plan_filter_var = tk.StringVar(value="ALL")
|
| 118 |
|
| 119 |
self.dc_lambda_var = tk.DoubleVar(value=1.0)
|
| 120 |
self.vw_lambda_var = tk.DoubleVar(value=1.0)
|
|
|
|
| 148 |
self.workers_var,
|
| 149 |
self.device_var,
|
| 150 |
self.use_spectral_var,
|
| 151 |
+
self.q4_fallback_var,
|
| 152 |
+
self.embd_q4_var,
|
| 153 |
+
self.promote_attn_q4_var,
|
| 154 |
+
self.quant_format_var,
|
| 155 |
):
|
| 156 |
v.trace_add("write", lambda *_: self._update_cli_preview())
|
| 157 |
|
|
|
|
| 187 |
style.map("Treeview", background=[("selected", accent)])
|
| 188 |
|
| 189 |
def _build_layout(self) -> None:
|
| 190 |
+
outer = ttk.Frame(self.root)
|
| 191 |
+
outer.pack(fill=tk.BOTH, expand=True)
|
| 192 |
+
outer.rowconfigure(0, weight=1)
|
| 193 |
+
outer.columnconfigure(0, weight=1)
|
| 194 |
+
|
| 195 |
+
self._canvas = tk.Canvas(outer, bg="#141820", highlightthickness=0)
|
| 196 |
+
v_scroll = ttk.Scrollbar(outer, orient=tk.VERTICAL, command=self._canvas.yview)
|
| 197 |
+
h_scroll = ttk.Scrollbar(outer, orient=tk.HORIZONTAL, command=self._canvas.xview)
|
| 198 |
+
self._canvas.configure(yscrollcommand=v_scroll.set, xscrollcommand=h_scroll.set)
|
| 199 |
+
|
| 200 |
+
self._canvas.grid(row=0, column=0, sticky=tk.NSEW)
|
| 201 |
+
v_scroll.grid(row=0, column=1, sticky=tk.NS)
|
| 202 |
+
h_scroll.grid(row=1, column=0, sticky=tk.EW)
|
| 203 |
+
|
| 204 |
+
main = ttk.Frame(self._canvas, padding=10)
|
| 205 |
+
self._canvas_win = self._canvas.create_window((0, 0), window=main, anchor=tk.NW)
|
| 206 |
+
|
| 207 |
+
def _on_frame_configure(_event=None) -> None:
|
| 208 |
+
self._canvas.configure(scrollregion=self._canvas.bbox("all"))
|
| 209 |
+
|
| 210 |
+
def _on_canvas_configure(event) -> None:
|
| 211 |
+
req_w = max(event.width, main.winfo_reqwidth())
|
| 212 |
+
req_h = max(event.height, main.winfo_reqheight())
|
| 213 |
+
self._canvas.itemconfigure(self._canvas_win, width=req_w, height=req_h)
|
| 214 |
+
|
| 215 |
+
main.bind("<Configure>", _on_frame_configure)
|
| 216 |
+
self._canvas.bind("<Configure>", _on_canvas_configure)
|
| 217 |
+
|
| 218 |
+
def _on_mousewheel(event) -> None:
|
| 219 |
+
w = event.widget
|
| 220 |
+
if isinstance(w, (ttk.Treeview, tk.Text)):
|
| 221 |
+
return
|
| 222 |
+
if getattr(event, "num", None) == 4:
|
| 223 |
+
self._canvas.yview_scroll(-1, "units")
|
| 224 |
+
elif getattr(event, "num", None) == 5:
|
| 225 |
+
self._canvas.yview_scroll(1, "units")
|
| 226 |
+
elif getattr(event, "delta", 0):
|
| 227 |
+
self._canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
|
| 228 |
+
|
| 229 |
+
self.root.bind_all("<MouseWheel>", _on_mousewheel)
|
| 230 |
+
self.root.bind_all("<Button-4>", _on_mousewheel)
|
| 231 |
+
self.root.bind_all("<Button-5>", _on_mousewheel)
|
| 232 |
|
| 233 |
# 1. File Selection Frame
|
| 234 |
files_frame = ttk.LabelFrame(main, text="1. GGUF & iMatrix Paths", padding=8)
|
|
|
|
| 266 |
mode_row.pack(fill=tk.X, pady=(0, 4))
|
| 267 |
ttk.Label(mode_row, text="Target Scope:").pack(side=tk.LEFT, padx=(0, 8))
|
| 268 |
ttk.Radiobutton(
|
| 269 |
+
mode_row, text="All Eligible Tensors", variable=self.mode_var, value="all"
|
| 270 |
).pack(side=tk.LEFT, padx=4)
|
| 271 |
ttk.Radiobutton(
|
| 272 |
mode_row, text="Selected Tensor(s)", variable=self.mode_var, value="selected"
|
| 273 |
).pack(side=tk.LEFT, padx=4)
|
| 274 |
|
| 275 |
+
fmt_row = ttk.Frame(opt_frame)
|
| 276 |
+
fmt_row.pack(fill=tk.X, pady=(0, 4))
|
| 277 |
+
ttk.Label(fmt_row, text="Quant Format:").pack(side=tk.LEFT, padx=(0, 8))
|
| 278 |
+
for lbl, val in (
|
| 279 |
+
("Mixed (Q2_K if eligible, else Q4_0)", "mixed"),
|
| 280 |
+
("Pure Q4_0", "q4_0"),
|
| 281 |
+
("Pure Q2_K", "q2_k"),
|
| 282 |
+
):
|
| 283 |
+
ttk.Radiobutton(
|
| 284 |
+
fmt_row,
|
| 285 |
+
text=lbl,
|
| 286 |
+
variable=self.quant_format_var,
|
| 287 |
+
value=val,
|
| 288 |
+
command=self._populate_tensor_tree,
|
| 289 |
+
).pack(side=tk.LEFT, padx=3)
|
| 290 |
+
|
| 291 |
opt_row = ttk.Frame(opt_frame)
|
| 292 |
opt_row.pack(fill=tk.X, pady=(0, 4))
|
| 293 |
ttk.Label(opt_row, text="Global Optimizer:").pack(side=tk.LEFT, padx=(0, 8))
|
|
|
|
| 330 |
text="Local-Safety Candidate & Factored Floors (Monotone Bound)",
|
| 331 |
variable=self.factor_floor_var,
|
| 332 |
).pack(anchor=tk.W, pady=1)
|
| 333 |
+
ttk.Checkbutton(
|
| 334 |
+
checks,
|
| 335 |
+
text="Q4_0 Fallback for 32-Aligned Non-Q2_K Tensors & Recurrent Gates (ssm_alpha/beta, ffn_down_exps, hc_*)",
|
| 336 |
+
variable=self.q4_fallback_var,
|
| 337 |
+
command=self._populate_tensor_tree,
|
| 338 |
+
).pack(anchor=tk.W, pady=1)
|
| 339 |
+
ttk.Checkbutton(
|
| 340 |
+
checks,
|
| 341 |
+
text="Quantize token_embd.weight & output.weight to Q4_0 (Saves 1.3–3.7 GB)",
|
| 342 |
+
variable=self.embd_q4_var,
|
| 343 |
+
command=self._populate_tensor_tree,
|
| 344 |
+
).pack(anchor=tk.W, pady=1)
|
| 345 |
+
ttk.Checkbutton(
|
| 346 |
+
checks,
|
| 347 |
+
text="Promote Attention Q/K/V/O Projections to Q4_0 (Mixed Q2_K + Q4_0)",
|
| 348 |
+
variable=self.promote_attn_q4_var,
|
| 349 |
+
command=self._populate_tensor_tree,
|
| 350 |
+
).pack(anchor=tk.W, pady=1)
|
| 351 |
|
| 352 |
grid_f = ttk.Frame(opt_frame)
|
| 353 |
grid_f.pack(fill=tk.X, pady=4)
|
|
|
|
| 386 |
|
| 387 |
search_row = ttk.Frame(browser_frame)
|
| 388 |
search_row.pack(fill=tk.X, pady=(0, 6))
|
| 389 |
+
ttk.Label(search_row, text="Filter:").pack(side=tk.LEFT, padx=(0, 4))
|
| 390 |
filter_entry = ttk.Entry(search_row, textvariable=self.filter_var)
|
| 391 |
filter_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
|
| 392 |
filter_entry.bind("<KeyRelease>", lambda _e: self._populate_tensor_tree())
|
| 393 |
+
for label, val in (("All", "ALL"), ("Q2_K", "Q2_K"), ("Q4_0", "Q4_0"), ("Copy", "COPY")):
|
| 394 |
+
ttk.Radiobutton(
|
| 395 |
+
search_row,
|
| 396 |
+
text=label,
|
| 397 |
+
variable=self.plan_filter_var,
|
| 398 |
+
value=val,
|
| 399 |
+
command=self._populate_tensor_tree,
|
| 400 |
+
).pack(side=tk.LEFT, padx=3)
|
| 401 |
ttk.Button(
|
| 402 |
+
search_row, text="Select Quantized", command=self._select_all_eligible
|
| 403 |
).pack(side=tk.LEFT, padx=4)
|
| 404 |
|
| 405 |
cols = ("name", "type", "dims", "row", "q2k", "imat", "state")
|
| 406 |
self.tree = ttk.Treeview(browser_frame, columns=cols, show="headings", selectmode="extended")
|
| 407 |
self.tree.heading("name", text="Tensor Name")
|
| 408 |
+
self.tree.heading("type", text="Source")
|
| 409 |
self.tree.heading("dims", text="Dims")
|
| 410 |
self.tree.heading("row", text="Row Width")
|
| 411 |
+
self.tree.heading("q2k", text="Target")
|
| 412 |
self.tree.heading("imat", text="iMatrix")
|
| 413 |
self.tree.heading("state", text="Live Status / RMSE")
|
| 414 |
+
self.tree.tag_configure("Q2_K", foreground="#93c5fd")
|
| 415 |
+
self.tree.tag_configure("Q4_0", foreground="#34d399")
|
| 416 |
+
self.tree.tag_configure("Copy", foreground="#9ca3af")
|
| 417 |
|
| 418 |
self.tree.column("name", width=220, anchor=tk.W)
|
| 419 |
self.tree.column("type", width=52, anchor=tk.CENTER)
|
|
|
|
| 591 |
vw_lambda=float(self.vw_lambda_var.get()),
|
| 592 |
dc_decay=float(self.dc_decay_var.get()),
|
| 593 |
sse_budget=float(self.sse_budget_var.get()),
|
| 594 |
+
quant_format=self.quant_format_var.get(),
|
| 595 |
+
enable_q4_fallback=bool(self.q4_fallback_var.get()) and self.quant_format_var.get() != "q2_k",
|
| 596 |
+
quantize_embd_q4=bool(self.embd_q4_var.get()),
|
| 597 |
+
promote_attn_q4=bool(self.promote_attn_q4_var.get()),
|
| 598 |
device=self.device_var.get(),
|
| 599 |
workers=int(self.workers_var.get()),
|
| 600 |
verbose=False,
|
|
|
|
| 619 |
cmd += ["--output", out]
|
| 620 |
if self.limit_var.get() > 0:
|
| 621 |
cmd += ["--limit", str(self.limit_var.get())]
|
| 622 |
+
cmd += ["--format", self.quant_format_var.get()]
|
| 623 |
cmd += ["--device", self.device_var.get()]
|
| 624 |
cmd += ["--workers", str(self.workers_var.get())]
|
| 625 |
cmd += ["--cand-d", str(self.cand_d_var.get()), "--cand-m", str(self.cand_m_var.get())]
|
|
|
|
| 627 |
cmd.append("--mse")
|
| 628 |
if not self.use_spectral_var.get():
|
| 629 |
cmd.append("--no-spectral")
|
| 630 |
+
if not self.q4_fallback_var.get():
|
| 631 |
+
cmd.append("--no-q4-fallback")
|
| 632 |
+
if not self.embd_q4_var.get():
|
| 633 |
+
cmd.append("--keep-embd")
|
| 634 |
+
if self.promote_attn_q4_var.get():
|
| 635 |
+
cmd.append("--promote-attn-q4")
|
| 636 |
cmd.append("--verbose")
|
| 637 |
return " ".join(shlex.quote(part) for part in cmd)
|
| 638 |
|
|
|
|
| 665 |
return
|
| 666 |
try:
|
| 667 |
self._reader = GGUFReader(gguf_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 668 |
self._populate_tensor_tree()
|
| 669 |
except Exception as exc:
|
| 670 |
self._reader = None
|
|
|
|
| 675 |
if self._reader is None:
|
| 676 |
return
|
| 677 |
filt = self.filter_var.get().strip().lower()
|
| 678 |
+
plan_filt = self.plan_filter_var.get()
|
| 679 |
+
n_q2, n_q4, n_copy = 0, 0, 0
|
| 680 |
for ti in self._reader.tensors:
|
| 681 |
+
tgt = target_quant_type(
|
| 682 |
+
ti.name,
|
| 683 |
+
ti.dims,
|
| 684 |
+
enable_q4_fallback=bool(self.q4_fallback_var.get()) and self.quant_format_var.get() != "q2_k",
|
| 685 |
+
quantize_embd_q4=bool(self.embd_q4_var.get()),
|
| 686 |
+
promote_attn_q4=bool(self.promote_attn_q4_var.get()),
|
| 687 |
+
quant_format=self.quant_format_var.get(),
|
| 688 |
+
source_type=ti.type,
|
| 689 |
+
)
|
| 690 |
+
if tgt == "Q2_K":
|
| 691 |
+
n_q2 += 1
|
| 692 |
+
elif tgt == "Q4_0":
|
| 693 |
+
n_q4 += 1
|
| 694 |
+
else:
|
| 695 |
+
n_copy += 1
|
| 696 |
+
|
| 697 |
+
tgt_label = tgt if tgt else "Copy"
|
| 698 |
+
if plan_filt != "ALL" and tgt_label.upper() != plan_filt:
|
| 699 |
+
continue
|
| 700 |
+
if (
|
| 701 |
+
filt
|
| 702 |
+
and filt not in ti.name.lower()
|
| 703 |
+
and filt not in ti.type_name.lower()
|
| 704 |
+
and filt not in tgt_label.lower()
|
| 705 |
+
):
|
| 706 |
continue
|
|
|
|
| 707 |
has_imat = (
|
| 708 |
self._imatrix is not None
|
| 709 |
and lookup_imatrix(self._imatrix, ti.name) is not None
|
| 710 |
)
|
| 711 |
+
state_str = (
|
| 712 |
+
f"Pending ({tgt_label})"
|
| 713 |
+
if tgt
|
| 714 |
+
else (f"Keep {ti.type_name} (<= target)" if ti.type_name in ("Q2_K", "Q4_0") else "Passthrough")
|
| 715 |
+
)
|
| 716 |
self.tree.insert(
|
| 717 |
"",
|
| 718 |
tk.END,
|
| 719 |
iid=ti.name,
|
| 720 |
+
tags=(tgt_label,),
|
| 721 |
values=(
|
| 722 |
ti.name,
|
| 723 |
ti.type_name,
|
| 724 |
str(ti.dims),
|
| 725 |
ti.row_width,
|
| 726 |
+
tgt_label,
|
| 727 |
"Yes" if has_imat else "-",
|
| 728 |
+
state_str,
|
| 729 |
),
|
| 730 |
)
|
| 731 |
+
self.status_var.set(
|
| 732 |
+
f"Plan ({self.quant_format_var.get().upper()}): {n_q2} Q2_K | {n_q4} Q4_0 | {n_copy} Copy (Total: {len(self._reader.tensors)} tensors)"
|
| 733 |
+
)
|
| 734 |
|
| 735 |
def _select_all_eligible(self) -> None:
|
| 736 |
if self._reader is None:
|
|
|
|
| 738 |
eligible_ids = [
|
| 739 |
ti.name
|
| 740 |
for ti in self._reader.tensors
|
| 741 |
+
if target_quant_type(
|
| 742 |
+
ti.name,
|
| 743 |
+
ti.dims,
|
| 744 |
+
enable_q4_fallback=bool(self.q4_fallback_var.get()) and self.quant_format_var.get() != "q2_k",
|
| 745 |
+
quantize_embd_q4=bool(self.embd_q4_var.get()),
|
| 746 |
+
promote_attn_q4=bool(self.promote_attn_q4_var.get()),
|
| 747 |
+
quant_format=self.quant_format_var.get(),
|
| 748 |
+
source_type=ti.type,
|
| 749 |
+
)
|
| 750 |
+
is not None
|
| 751 |
+
and self.tree.exists(ti.name)
|
| 752 |
]
|
| 753 |
self.tree.selection_set(eligible_ids)
|
| 754 |
|
|
|
|
| 880 |
self._log_queue.put(
|
| 881 |
(
|
| 882 |
"done",
|
| 883 |
+
f"Wrote {out_path}: {int(stats.get('q2_k', 0))} Q2_K + {int(stats.get('q4_0', 0))} Q4_0 "
|
| 884 |
+
f"({int(stats['quantized'])}/{int(stats['tensors'])} tensors), "
|
| 885 |
f"overall RMSE={stats['rmse']:.6e} ({dt_sec:.1f}s)",
|
| 886 |
)
|
| 887 |
)
|
|
|
|
| 1024 |
done, total, name, action, rmse, has_imat = payload # type: ignore[misc]
|
| 1025 |
self.model_progress_var.set(100.0 * done / max(total, 1))
|
| 1026 |
self.tensor_progress_var.set(100.0)
|
| 1027 |
+
if action in ("Q2_K", "Q4_0") and rmse is not None:
|
| 1028 |
+
self._update_tree_row_state(name, f"{action} (RMSE={rmse:.4e})")
|
| 1029 |
self._log(
|
| 1030 |
+
f"[{done}/{total}] FINISHED {name:42s} -> {action} RMSE={rmse:.6e} (iMatrix={'yes' if has_imat else 'no'})"
|
| 1031 |
)
|
| 1032 |
else:
|
| 1033 |
self._update_tree_row_state(name, "Copied verbatim")
|
q4_0.py
ADDED
|
@@ -0,0 +1,444 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Full HPC V2 Q4_0 quantizer (CUDA GPU + Vectorized CPU).
|
| 2 |
+
|
| 3 |
+
Implements the complete HPC-Quantize V2 decision stack for ``Q4_0`` (32 weights
|
| 4 |
+
per 18-byte block = 4.5 bpw):
|
| 5 |
+
|
| 6 |
+
1. **Geometry-Preserving Analog + WLS Seeds**:
|
| 7 |
+
Finds optimal ``d*`` from both the raw weights and an iso-moment companded
|
| 8 |
+
analog of each 32-weight block.
|
| 9 |
+
2. **24-Candidate Scale Lattice & Extended Spectral Objective**:
|
| 10 |
+
Evaluates 24 scale multipliers (mapped to 6 symbolic quhit states) on
|
| 11 |
+
importance-weighted SSE + D6/Vesica fold pyramid + DC penalty, including
|
| 12 |
+
negative-scale sign-flip candidates ``-d`` (which mirror the asymmetric
|
| 13 |
+
``[-8, +7]`` grid to ``[-7, +8]`` when positive outliers dominate).
|
| 14 |
+
3. **6-State Sequential Sieve & 6-State Viterbi DP**:
|
| 15 |
+
Runs the 6-state sequential Sieve with parity back-action and a 6-state
|
| 16 |
+
Viterbi dynamic program with free-energy bin reduction and Manhattan
|
| 17 |
+
transition penalty across the block chain.
|
| 18 |
+
4. **Asymmetric Sign-Flip fp16-ULP Polish & Closed-Form Vesica/DC Shaping**:
|
| 19 |
+
Polishes ``d`` over ``+/-8`` fp16 ULPs of both ``+d`` and ``-d``, and
|
| 20 |
+
applies closed-form 1-D quadratic Vesica + DC code projection bounded by
|
| 21 |
+
``sse_budget`` plus a strict monotone candidate floor.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
from __future__ import annotations
|
| 25 |
+
|
| 26 |
+
from math import ceil
|
| 27 |
+
import numpy as np
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
import torch
|
| 31 |
+
except ImportError: # pragma: no cover
|
| 32 |
+
torch = None # type: ignore[assignment]
|
| 33 |
+
|
| 34 |
+
from .config import HPCConfig
|
| 35 |
+
from .cuda_backend import cuda_is_available
|
| 36 |
+
from .factored import CAND_TO_QUHIT, MULTS_D
|
| 37 |
+
from .fp16 import from_fp16_bits, nearest_int, to_fp16_bits
|
| 38 |
+
from .sieve import sieve_measure_chain, subblock_chain_edges
|
| 39 |
+
from .viterbi import robust_temperature
|
| 40 |
+
|
| 41 |
+
QK4_0 = 32
|
| 42 |
+
Q4_0_BLOCK_BYTES = 18
|
| 43 |
+
Q4_N_CAND = 24
|
| 44 |
+
Q4_N_STATES = 6
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def dequantize_q4_0_bytes(raw: bytes | np.ndarray, n_blocks: int) -> np.ndarray:
|
| 48 |
+
blocks = np.frombuffer(raw, dtype=np.uint8).reshape(n_blocks, Q4_0_BLOCK_BYTES)
|
| 49 |
+
d = blocks[:, :2].copy().view("<f2").reshape(n_blocks, 1).astype(np.float32)
|
| 50 |
+
qs = blocks[:, 2:]
|
| 51 |
+
low = (qs & 0x0F).astype(np.float32) - 8.0
|
| 52 |
+
high = (qs >> 4).astype(np.float32) - 8.0
|
| 53 |
+
q = np.concatenate([low, high], axis=1)
|
| 54 |
+
return (d * q).reshape(-1)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _q4_sieve_and_viterbi(cand_errors: np.ndarray, cfg: HPCConfig) -> np.ndarray:
|
| 58 |
+
"""6-state sequential Sieve + 6-state Viterbi DP over Q4_0 candidate lattice."""
|
| 59 |
+
B = cand_errors.shape[0]
|
| 60 |
+
if cfg.optimizer != "hpc" or B < 2:
|
| 61 |
+
return np.argmin(cand_errors, axis=1).astype(np.int64)
|
| 62 |
+
|
| 63 |
+
max_gb = min(int(cfg.graph_max_blocks), 512)
|
| 64 |
+
stride = max(1, ceil(B / max_gb))
|
| 65 |
+
gb = ceil(B / stride)
|
| 66 |
+
temp = max(float(robust_temperature(cand_errors, cfg)), 1.0e-12)
|
| 67 |
+
|
| 68 |
+
pad = gb * stride - B
|
| 69 |
+
ce = cand_errors.astype(np.float64)
|
| 70 |
+
if pad > 0:
|
| 71 |
+
ce = np.concatenate([ce, np.full((pad, Q4_N_CAND), np.inf, dtype=np.float64)], axis=0)
|
| 72 |
+
ce_grouped = ce.reshape(gb, stride, Q4_N_STATES, 4)
|
| 73 |
+
|
| 74 |
+
group_min = np.min(ce_grouped, axis=(1, 3)) # (gb, 6)
|
| 75 |
+
finite = np.isfinite(ce_grouped)
|
| 76 |
+
counts = np.sum(finite, axis=(1, 3))
|
| 77 |
+
valid = (counts > 0) & np.isfinite(group_min)
|
| 78 |
+
gm_b = np.where(np.isfinite(group_min), group_min, 0.0)[:, None, :, None]
|
| 79 |
+
shifted = np.where(finite, (ce_grouped - gm_b) / (2.0 * temp), np.inf)
|
| 80 |
+
sums = np.sum(np.exp(-shifted), axis=(1, 3))
|
| 81 |
+
mean_exp = np.maximum(sums / np.maximum(counts, 1), 1.0e-300)
|
| 82 |
+
bin_err = np.where(valid, group_min - 2.0 * temp * np.log(mean_exp), np.inf)
|
| 83 |
+
|
| 84 |
+
# Sieve local amplitudes from mean candidate errors per group:
|
| 85 |
+
agg = np.mean(np.where(finite, ce_grouped, 0.0), axis=1).reshape(gb, Q4_N_CAND)
|
| 86 |
+
mn = np.min(agg, axis=1, keepdims=True)
|
| 87 |
+
coeff = np.exp(-np.clip((agg - mn) / (2.0 * temp), 0.0, 80.0)).reshape(gb, Q4_N_STATES, 4)
|
| 88 |
+
amps = np.sum(coeff, axis=2)
|
| 89 |
+
norms = np.linalg.norm(amps, axis=1, keepdims=True)
|
| 90 |
+
amps = np.where(norms > 1.0e-30, amps / np.maximum(norms, 1.0e-30), 1.0 / np.sqrt(6.0))
|
| 91 |
+
|
| 92 |
+
marg, _ = sieve_measure_chain(
|
| 93 |
+
amps,
|
| 94 |
+
subblock_chain_edges(gb),
|
| 95 |
+
same_penalty=cfg.same_penalty,
|
| 96 |
+
log_slack=cfg.log_slack,
|
| 97 |
+
deterministic=True,
|
| 98 |
+
)
|
| 99 |
+
m_tot = np.sum(marg, axis=1, keepdims=True)
|
| 100 |
+
pm = np.where(m_tot > 1.0e-30, marg / np.maximum(m_tot, 1.0e-30), 1.0 / 6.0)
|
| 101 |
+
log_prior = np.log(pm + 1.0e-30)
|
| 102 |
+
|
| 103 |
+
fin_err = bin_err[np.isfinite(bin_err)]
|
| 104 |
+
scale_err = max(float(fin_err.mean()) if fin_err.size else 1.0e-10, 1.0e-20)
|
| 105 |
+
local = np.where(np.isfinite(bin_err), bin_err - cfg.viterbi_beta * scale_err * log_prior, np.inf)
|
| 106 |
+
|
| 107 |
+
states = np.arange(Q4_N_STATES)
|
| 108 |
+
trans = cfg.viterbi_alpha * scale_err * np.abs(states[None, :] - states[:, None])
|
| 109 |
+
dp = np.full((gb, Q4_N_STATES), np.inf, dtype=np.float64)
|
| 110 |
+
back = np.zeros((gb, Q4_N_STATES), dtype=np.int64)
|
| 111 |
+
dp[0] = local[0]
|
| 112 |
+
for gi in range(1, gb):
|
| 113 |
+
totals = dp[gi - 1][:, None] + trans
|
| 114 |
+
best_sp = np.argmin(totals, axis=0)
|
| 115 |
+
best_val = totals[best_sp, states]
|
| 116 |
+
dp[gi] = np.where(np.isfinite(best_val), best_val + local[gi], np.inf)
|
| 117 |
+
back[gi] = best_sp
|
| 118 |
+
|
| 119 |
+
path = np.zeros(gb, dtype=np.int64)
|
| 120 |
+
if np.any(np.isfinite(dp[-1])):
|
| 121 |
+
path[-1] = int(np.argmin(dp[-1]))
|
| 122 |
+
for gi in range(gb - 2, -1, -1):
|
| 123 |
+
path[gi] = back[gi + 1, path[gi + 1]]
|
| 124 |
+
|
| 125 |
+
ce_bins = cand_errors.reshape(B, Q4_N_STATES, 4)
|
| 126 |
+
bin_local_arg = np.argmin(ce_bins, axis=2) # (B, 6)
|
| 127 |
+
blk_gi = np.arange(B) // stride
|
| 128 |
+
chosen_bin = path[blk_gi]
|
| 129 |
+
chosen_cand = chosen_bin * 4 + bin_local_arg[np.arange(B), chosen_bin]
|
| 130 |
+
|
| 131 |
+
global_best = np.argmin(cand_errors, axis=1).astype(np.int64)
|
| 132 |
+
cur_e = cand_errors[np.arange(B), chosen_cand]
|
| 133 |
+
g_e = cand_errors[np.arange(B), global_best]
|
| 134 |
+
return np.where(g_e < cur_e * cfg.greedy_override_ratio, global_best, chosen_cand)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def _quantize_q4_0_hpc_cpu(
|
| 138 |
+
X: np.ndarray, W: np.ndarray, cfg: HPCConfig
|
| 139 |
+
) -> tuple[bytes, float]:
|
| 140 |
+
"""Full HPC V2 Q4_0 pipeline on CPU for a chunk of (B, 32) blocks."""
|
| 141 |
+
B = X.shape[0]
|
| 142 |
+
X_f32 = X.astype(np.float32)
|
| 143 |
+
W_f32 = W.astype(np.float32)
|
| 144 |
+
lam_dc = (float(cfg.dc_lambda) / QK4_0) if cfg.use_spectral else 0.0
|
| 145 |
+
lam_vw = (float(cfg.vw_lambda) / QK4_0) if cfg.use_spectral else 0.0
|
| 146 |
+
half = QK4_0 // 2
|
| 147 |
+
|
| 148 |
+
# 1. Analog + WLS seed for d* (testing both +d and asymmetric sign-flip -d):
|
| 149 |
+
amax = np.max(np.abs(X_f32), axis=1)
|
| 150 |
+
d_range = amax / 7.5
|
| 151 |
+
wsum = np.maximum(np.sum(W_f32, axis=1, keepdims=True), 1.0e-30)
|
| 152 |
+
mu = np.sum(W_f32 * X_f32, axis=1, keepdims=True) / wsum
|
| 153 |
+
var = np.sum(W_f32 * (X_f32 - mu) ** 2, axis=1, keepdims=True) / wsum
|
| 154 |
+
sig = np.sqrt(np.maximum(var, 1.0e-30))
|
| 155 |
+
x_comp = mu + sig * 1.85 * np.tanh((X_f32 - mu) / (1.85 * sig))
|
| 156 |
+
d_analog = np.max(np.abs(x_comp), axis=1).astype(np.float32) / 7.5
|
| 157 |
+
|
| 158 |
+
wls_d = d_range.copy()
|
| 159 |
+
best_seed_sse = np.full(B, np.inf, dtype=np.float64)
|
| 160 |
+
for d_start in (d_range, -d_range, d_analog, -d_analog):
|
| 161 |
+
d = d_start.astype(np.float64)
|
| 162 |
+
for _ in range(4):
|
| 163 |
+
act = np.abs(d) > 1.0e-15
|
| 164 |
+
sd = np.where(act, d, 1.0)[:, None]
|
| 165 |
+
q = np.where(act[:, None], np.clip(nearest_int((X_f32 / sd).astype(np.float32)) + 8, 0, 15), 8)
|
| 166 |
+
c = (q - 8).astype(np.float64)
|
| 167 |
+
num = np.sum(W_f32 * X_f32 * c, axis=1, dtype=np.float64)
|
| 168 |
+
den = np.sum(W_f32 * c * c, axis=1, dtype=np.float64)
|
| 169 |
+
valid = den > 1.0e-30
|
| 170 |
+
d = np.where(valid, num / np.where(valid, den, 1.0), 0.0)
|
| 171 |
+
df = from_fp16_bits(to_fp16_bits(d.astype(np.float32)))
|
| 172 |
+
act = np.abs(df) > 1.0e-15
|
| 173 |
+
sdf = np.where(act, df, 1.0)[:, None]
|
| 174 |
+
q = np.where(act[:, None], np.clip(nearest_int(X_f32 / sdf) + 8, 0, 15), 8)
|
| 175 |
+
e = X_f32 - df[:, None] * (q.astype(np.float32) - 8.0)
|
| 176 |
+
sse = np.sum(W_f32 * e * e, axis=1, dtype=np.float64)
|
| 177 |
+
take = sse < best_seed_sse
|
| 178 |
+
best_seed_sse = np.where(take, sse, best_seed_sse)
|
| 179 |
+
wls_d = np.where(take, df, wls_d)
|
| 180 |
+
|
| 181 |
+
# 2. 24-Candidate Field with Extended Spectral Objective:
|
| 182 |
+
cand_d16 = to_fp16_bits(wls_d[:, None] * MULTS_D[None, :]) # (B, 24)
|
| 183 |
+
cand_d = from_fp16_bits(cand_d16) # (B, 24)
|
| 184 |
+
act_c = np.abs(cand_d) > 1.0e-15
|
| 185 |
+
sd_c = np.where(act_c, cand_d, 1.0)[:, :, None]
|
| 186 |
+
q_c = np.where(
|
| 187 |
+
act_c[:, :, None],
|
| 188 |
+
np.clip(nearest_int(X_f32[:, None, :] / sd_c) + 8, 0, 15),
|
| 189 |
+
8,
|
| 190 |
+
).astype(np.float32)
|
| 191 |
+
e_c = X_f32[:, None, :] - cand_d[:, :, None] * (q_c - 8.0) # (B, 24, 32)
|
| 192 |
+
sse_c = np.sum(W_f32[:, None, :] * e_c * e_c, axis=2)
|
| 193 |
+
if cfg.use_spectral and (lam_dc > 0.0 or lam_vw > 0.0):
|
| 194 |
+
v_c = e_c[:, :, :half] + e_c[:, :, half:]
|
| 195 |
+
dc_c = np.sum(e_c, axis=2)
|
| 196 |
+
cand_errors = (sse_c + lam_vw * np.sum(v_c * v_c, axis=2) + lam_dc * dc_c * dc_c).astype(np.float32)
|
| 197 |
+
else:
|
| 198 |
+
cand_errors = sse_c.astype(np.float32)
|
| 199 |
+
|
| 200 |
+
# 3. 6-State Sieve + 6-State Viterbi DP:
|
| 201 |
+
best_cand = _q4_sieve_and_viterbi(cand_errors, cfg)
|
| 202 |
+
rows = np.arange(B)
|
| 203 |
+
d_sel = cand_d[rows, best_cand]
|
| 204 |
+
|
| 205 |
+
# 4. Asymmetric Sign-Flip fp16-ULP Polish (+/-8 ULPs around +d_sel and -d_sel):
|
| 206 |
+
rad = max(int(cfg.ulp_radius), 4)
|
| 207 |
+
deltas = np.arange(-rad, rad + 1, dtype=np.int32)
|
| 208 |
+
pos_b = np.clip(to_fp16_bits(np.abs(d_sel)).astype(np.int32)[:, None] + deltas[None, :], 0, 0x7BFF).astype(np.uint16)
|
| 209 |
+
neg_b = (pos_b | np.uint16(0x8000)).astype(np.uint16)
|
| 210 |
+
all_b = np.concatenate([pos_b, neg_b], axis=1) # (B, 2*(2*rad+1))
|
| 211 |
+
all_d = from_fp16_bits(all_b)
|
| 212 |
+
act_u = np.abs(all_d) > 1.0e-15
|
| 213 |
+
sd_u = np.where(act_u, all_d, 1.0)[:, :, None]
|
| 214 |
+
q_u = np.where(
|
| 215 |
+
act_u[:, :, None],
|
| 216 |
+
np.clip(nearest_int(X_f32[:, None, :] / sd_u) + 8, 0, 15),
|
| 217 |
+
8,
|
| 218 |
+
).astype(np.uint8)
|
| 219 |
+
e_u = X_f32[:, None, :] - all_d[:, :, None] * (q_u.astype(np.float32) - 8.0)
|
| 220 |
+
sse_u = np.sum(W_f32[:, None, :] * e_u * e_u, axis=2, dtype=np.float64)
|
| 221 |
+
pick_u = np.argmin(sse_u, axis=1)
|
| 222 |
+
best_d16 = all_b[rows, pick_u]
|
| 223 |
+
best_d = all_d[rows, pick_u]
|
| 224 |
+
best_q = q_u[rows, pick_u].astype(np.int64)
|
| 225 |
+
|
| 226 |
+
# 5. Closed-Form 1-D Quadratic Vesica + DC Code Projection within sse_budget:
|
| 227 |
+
if cfg.use_spectral and (lam_vw > 0.0 or lam_dc > 0.0):
|
| 228 |
+
c_f = (best_q - 8).astype(np.float64)
|
| 229 |
+
e = X_f32.astype(np.float64) - best_d[:, None].astype(np.float64) * c_f
|
| 230 |
+
sse_live = np.sum(W_f32 * e * e, axis=1, dtype=np.float64)
|
| 231 |
+
sse_cap = sse_live * (1.0 + cfg.sse_budget)
|
| 232 |
+
v = e[:, :half] + e[:, half:]
|
| 233 |
+
dc = np.sum(e, axis=1)
|
| 234 |
+
d_f64 = best_d.astype(np.float64)[:, None]
|
| 235 |
+
denom = (W_f32 + lam_vw + lam_dc) * (d_f64 * d_f64)
|
| 236 |
+
act_b = np.abs(d_f64) > 1.0e-15
|
| 237 |
+
s_den = np.where(act_b & (denom > 1.0e-30), denom, 1.0)
|
| 238 |
+
v_full = np.concatenate([v, v], axis=1)
|
| 239 |
+
grad = d_f64 * (W_f32 * e + lam_vw * v_full + lam_dc * dc[:, None])
|
| 240 |
+
dq = np.where(act_b, nearest_int((grad / s_den).astype(np.float32)), 0)
|
| 241 |
+
q_new = np.clip(best_q + dq, 0, 15)
|
| 242 |
+
e_new = X_f32.astype(np.float64) - d_f64 * (q_new - 8).astype(np.float64)
|
| 243 |
+
sse_new = np.sum(W_f32 * e_new * e_new, axis=1, dtype=np.float64)
|
| 244 |
+
v_new = e_new[:, :half] + e_new[:, half:]
|
| 245 |
+
dc_new = np.sum(e_new, axis=1)
|
| 246 |
+
spec_old = lam_vw * np.sum(v * v, axis=1) + lam_dc * dc * dc
|
| 247 |
+
spec_new = lam_vw * np.sum(v_new * v_new, axis=1) + lam_dc * dc_new * dc_new
|
| 248 |
+
accept = (sse_new <= sse_cap) & ((sse_new + spec_new) < (sse_live + spec_old) - 1.0e-15)
|
| 249 |
+
best_q = np.where(accept[:, None], q_new, best_q)
|
| 250 |
+
|
| 251 |
+
best_q_u8 = best_q.astype(np.uint8)
|
| 252 |
+
out = np.empty((B, Q4_0_BLOCK_BYTES), dtype=np.uint8)
|
| 253 |
+
out[:, :2] = best_d16.astype("<u2").view(np.uint8).reshape(B, 2)
|
| 254 |
+
out[:, 2:] = (best_q_u8[:, :16] & 0x0F) | ((best_q_u8[:, 16:] & 0x0F) << np.uint8(4))
|
| 255 |
+
|
| 256 |
+
deq_final = best_d[:, None] * (best_q_u8.astype(np.float32) - 8.0)
|
| 257 |
+
raw_sse = float(np.sum((X_f32 - deq_final) ** 2, dtype=np.float64))
|
| 258 |
+
return out.tobytes(), raw_sse
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def _quantize_q4_0_hpc_cuda(
|
| 262 |
+
X_np: np.ndarray, W_np: np.ndarray, dev: "torch.device", cfg: HPCConfig
|
| 263 |
+
) -> tuple[bytes, float]:
|
| 264 |
+
"""Full HPC V2 Q4_0 pipeline on CUDA GPU for a chunk of (B, 32) blocks."""
|
| 265 |
+
B = X_np.shape[0]
|
| 266 |
+
lam_dc = (float(cfg.dc_lambda) / QK4_0) if cfg.use_spectral else 0.0
|
| 267 |
+
lam_vw = (float(cfg.vw_lambda) / QK4_0) if cfg.use_spectral else 0.0
|
| 268 |
+
half = QK4_0 // 2
|
| 269 |
+
|
| 270 |
+
with torch.no_grad():
|
| 271 |
+
X = torch.from_numpy(X_np).to(dev, dtype=torch.float32)
|
| 272 |
+
W = torch.from_numpy(W_np).to(dev, dtype=torch.float32)
|
| 273 |
+
|
| 274 |
+
# 1. Analog + WLS seed (including negative-scale sign-flip starts):
|
| 275 |
+
amax = torch.max(torch.abs(X), dim=1).values
|
| 276 |
+
d_range = amax / 7.5
|
| 277 |
+
wsum = torch.clamp(torch.sum(W, dim=1, keepdim=True), min=1.0e-30)
|
| 278 |
+
mu = torch.sum(W * X, dim=1, keepdim=True) / wsum
|
| 279 |
+
var = torch.sum(W * (X - mu) ** 2, dim=1, keepdim=True) / wsum
|
| 280 |
+
sig = torch.sqrt(torch.clamp(var, min=1.0e-30))
|
| 281 |
+
x_comp = mu + sig * 1.85 * torch.tanh((X - mu) / (1.85 * sig))
|
| 282 |
+
d_analog = torch.max(torch.abs(x_comp), dim=1).values / 7.5
|
| 283 |
+
|
| 284 |
+
wls_d = d_range.clone()
|
| 285 |
+
best_seed_sse = torch.full((B,), float("inf"), dtype=torch.float32, device=dev)
|
| 286 |
+
for d_start in (d_range, -d_range, d_analog, -d_analog):
|
| 287 |
+
d = d_start.clone()
|
| 288 |
+
for _ in range(4):
|
| 289 |
+
act = torch.abs(d) > 1.0e-15
|
| 290 |
+
sd = torch.where(act, d, torch.ones_like(d))[:, None]
|
| 291 |
+
sh = (X / sd) + 12582912.0
|
| 292 |
+
qi = ((sh.view(torch.int32) & 0x007FFFFF) - 0x00400000 + 8).clamp(0, 15)
|
| 293 |
+
q = torch.where(act[:, None], qi, torch.full_like(qi, 8))
|
| 294 |
+
c = (q - 8).to(torch.float32)
|
| 295 |
+
num = torch.sum(W * X * c, dim=1)
|
| 296 |
+
den = torch.sum(W * c * c, dim=1)
|
| 297 |
+
valid = den > 1.0e-30
|
| 298 |
+
d = torch.where(valid, num / torch.where(valid, den, torch.ones_like(den)), torch.zeros_like(den))
|
| 299 |
+
df = d.to(torch.float16).to(torch.float32)
|
| 300 |
+
act = torch.abs(df) > 1.0e-15
|
| 301 |
+
sdf = torch.where(act, df, torch.ones_like(df))[:, None]
|
| 302 |
+
sh = (X / sdf) + 12582912.0
|
| 303 |
+
qi = ((sh.view(torch.int32) & 0x007FFFFF) - 0x00400000 + 8).clamp(0, 15)
|
| 304 |
+
q = torch.where(act[:, None], qi, torch.full_like(qi, 8))
|
| 305 |
+
e = X - df[:, None] * (q.to(torch.float32) - 8.0)
|
| 306 |
+
sse = torch.sum(W * e * e, dim=1)
|
| 307 |
+
take = sse < best_seed_sse
|
| 308 |
+
best_seed_sse = torch.where(take, sse, best_seed_sse)
|
| 309 |
+
wls_d = torch.where(take, df, wls_d)
|
| 310 |
+
|
| 311 |
+
# 2. 24-Candidate Field with Extended Spectral Objective on GPU:
|
| 312 |
+
mults = torch.tensor(MULTS_D, dtype=torch.float32, device=dev)
|
| 313 |
+
cand_d = (wls_d[:, None] * mults[None, :]).to(torch.float16).to(torch.float32) # (B, 24)
|
| 314 |
+
act_c = torch.abs(cand_d) > 1.0e-15
|
| 315 |
+
sd_c = torch.where(act_c, cand_d, torch.ones_like(cand_d))[:, :, None]
|
| 316 |
+
sh_c = (X[:, None, :] / sd_c) + 12582912.0
|
| 317 |
+
qi_c = ((sh_c.view(torch.int32) & 0x007FFFFF) - 0x00400000 + 8).clamp(0, 15)
|
| 318 |
+
q_c = torch.where(act_c[:, :, None], qi_c, torch.full_like(qi_c, 8)).to(torch.float32)
|
| 319 |
+
e_c = X[:, None, :] - cand_d[:, :, None] * (q_c - 8.0)
|
| 320 |
+
sse_c = torch.sum(W[:, None, :] * e_c * e_c, dim=2)
|
| 321 |
+
if cfg.use_spectral and (lam_dc > 0.0 or lam_vw > 0.0):
|
| 322 |
+
v_c = e_c[:, :, :half] + e_c[:, :, half:]
|
| 323 |
+
dc_c = torch.sum(e_c, dim=2)
|
| 324 |
+
cand_err_t = sse_c + lam_vw * torch.sum(v_c * v_c, dim=2) + lam_dc * dc_c * dc_c
|
| 325 |
+
else:
|
| 326 |
+
cand_err_t = sse_c
|
| 327 |
+
|
| 328 |
+
# 3. 6-State Sieve + 6-State Viterbi DP:
|
| 329 |
+
best_cand_np = _q4_sieve_and_viterbi(cand_err_t.cpu().numpy(), cfg)
|
| 330 |
+
best_cand_t = torch.from_numpy(best_cand_np).to(dev)
|
| 331 |
+
rows = torch.arange(B, device=dev)
|
| 332 |
+
d_sel = cand_d[rows, best_cand_t]
|
| 333 |
+
|
| 334 |
+
# 4. Asymmetric Sign-Flip fp16-ULP Polish (+/-8 ULPs around +d_sel and -d_sel):
|
| 335 |
+
rad = max(int(cfg.ulp_radius), 4)
|
| 336 |
+
deltas = torch.arange(-rad, rad + 1, dtype=torch.int32, device=dev)
|
| 337 |
+
abs_bits = torch.abs(d_sel).to(torch.float16).view(torch.int16).to(torch.int32) & 0x7FFF
|
| 338 |
+
pos_b = torch.clamp(abs_bits[:, None] + deltas[None, :], 0, 0x7BFF)
|
| 339 |
+
neg_b = pos_b | 0x8000
|
| 340 |
+
all_b = torch.cat([pos_b, neg_b], dim=1) # (B, 2*(2*rad+1))
|
| 341 |
+
all_d = all_b.to(torch.int16).view(torch.float16).to(torch.float32)
|
| 342 |
+
act_u = torch.abs(all_d) > 1.0e-15
|
| 343 |
+
sd_u = torch.where(act_u, all_d, torch.ones_like(all_d))[:, :, None]
|
| 344 |
+
sh_u = (X[:, None, :] / sd_u) + 12582912.0
|
| 345 |
+
qi_u = ((sh_u.view(torch.int32) & 0x007FFFFF) - 0x00400000 + 8).clamp(0, 15)
|
| 346 |
+
q_u = torch.where(act_u[:, :, None], qi_u, torch.full_like(qi_u, 8)).to(torch.uint8)
|
| 347 |
+
e_u = X[:, None, :] - all_d[:, :, None] * (q_u.to(torch.float32) - 8.0)
|
| 348 |
+
sse_u = torch.sum(W[:, None, :] * e_u * e_u, dim=2)
|
| 349 |
+
pick_u = torch.argmin(sse_u, dim=1)
|
| 350 |
+
best_d16 = all_b[rows, pick_u]
|
| 351 |
+
best_d = all_d[rows, pick_u]
|
| 352 |
+
best_q = q_u[rows, pick_u].to(torch.int64)
|
| 353 |
+
|
| 354 |
+
# 5. Closed-Form 1-D Quadratic Vesica + DC Code Projection within sse_budget:
|
| 355 |
+
if cfg.use_spectral and (lam_vw > 0.0 or lam_dc > 0.0):
|
| 356 |
+
d_col = best_d[:, None]
|
| 357 |
+
e = X - d_col * (best_q.to(torch.float32) - 8.0)
|
| 358 |
+
sse_live = torch.sum(W * e * e, dim=1)
|
| 359 |
+
sse_cap = sse_live * (1.0 + float(cfg.sse_budget))
|
| 360 |
+
v = e[:, :half] + e[:, half:]
|
| 361 |
+
dc = torch.sum(e, dim=1)
|
| 362 |
+
denom = (W + lam_vw + lam_dc) * (d_col * d_col)
|
| 363 |
+
act_b = torch.abs(d_col) > 1.0e-15
|
| 364 |
+
s_den = torch.where(act_b & (denom > 1.0e-30), denom, torch.ones_like(denom))
|
| 365 |
+
v_full = torch.cat([v, v], dim=1)
|
| 366 |
+
grad = d_col * (W * e + lam_vw * v_full + lam_dc * dc[:, None])
|
| 367 |
+
sh_dq = (grad / s_den) + 12582912.0
|
| 368 |
+
dq = torch.where(
|
| 369 |
+
act_b,
|
| 370 |
+
((sh_dq.view(torch.int32) & 0x007FFFFF) - 0x00400000).to(torch.int64),
|
| 371 |
+
torch.zeros_like(best_q),
|
| 372 |
+
)
|
| 373 |
+
q_new = torch.clamp(best_q + dq, 0, 15)
|
| 374 |
+
e_new = X - d_col * (q_new.to(torch.float32) - 8.0)
|
| 375 |
+
sse_new = torch.sum(W * e_new * e_new, dim=1)
|
| 376 |
+
v_new = e_new[:, :half] + e_new[:, half:]
|
| 377 |
+
dc_new = torch.sum(e_new, dim=1)
|
| 378 |
+
spec_old = lam_vw * torch.sum(v * v, dim=1) + lam_dc * dc * dc
|
| 379 |
+
spec_new = lam_vw * torch.sum(v_new * v_new, dim=1) + lam_dc * dc_new * dc_new
|
| 380 |
+
accept = (sse_new <= sse_cap) & ((sse_new + spec_new) < (sse_live + spec_old) - 1.0e-12)
|
| 381 |
+
best_q = torch.where(accept[:, None], q_new, best_q)
|
| 382 |
+
|
| 383 |
+
best_q_u8 = best_q.to(torch.uint8)
|
| 384 |
+
deq_fin = best_d[:, None] * (best_q_u8.to(torch.float32) - 8.0)
|
| 385 |
+
raw_sse = float(torch.sum((X - deq_fin) ** 2, dtype=torch.float64).item())
|
| 386 |
+
|
| 387 |
+
d16_np = best_d16.to(torch.int16).cpu().numpy().view(np.uint16)
|
| 388 |
+
q_np = best_q_u8.cpu().numpy()
|
| 389 |
+
out = np.empty((B, Q4_0_BLOCK_BYTES), dtype=np.uint8)
|
| 390 |
+
out[:, :2] = d16_np.astype("<u2").view(np.uint8).reshape(B, 2)
|
| 391 |
+
out[:, 2:] = (q_np[:, :16] & 0x0F) | ((q_np[:, 16:] & 0x0F) << np.uint8(4))
|
| 392 |
+
return out.tobytes(), raw_sse
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def quantize_tensor_q4_0(
|
| 396 |
+
weights: np.ndarray,
|
| 397 |
+
importance: np.ndarray | None = None,
|
| 398 |
+
cfg: HPCConfig | None = None,
|
| 399 |
+
chunk_blocks: int = 131072,
|
| 400 |
+
) -> tuple[bytes, int, float]:
|
| 401 |
+
"""Quantize a tensor to GGML Q4_0 using the full HPC V2 pipeline."""
|
| 402 |
+
cfg = cfg or HPCConfig()
|
| 403 |
+
x = np.asarray(weights, dtype=np.float32).ravel()
|
| 404 |
+
if x.size == 0 or x.size % QK4_0 != 0:
|
| 405 |
+
raise ValueError("Q4_0 requires a non-empty weight count divisible by 32")
|
| 406 |
+
n_blocks = x.size // QK4_0
|
| 407 |
+
X = x.reshape(n_blocks, QK4_0)
|
| 408 |
+
|
| 409 |
+
if importance is not None:
|
| 410 |
+
imp = np.asarray(importance, dtype=np.float32).ravel()
|
| 411 |
+
if imp.size != x.size:
|
| 412 |
+
raise ValueError("importance length must match weight count")
|
| 413 |
+
W_raw = imp.reshape(n_blocks, QK4_0)
|
| 414 |
+
else:
|
| 415 |
+
W_raw = None
|
| 416 |
+
|
| 417 |
+
use_cuda = cfg.device != "cpu" and cuda_is_available() and (
|
| 418 |
+
cfg.device.startswith("cuda") or (cfg.device == "auto" and n_blocks >= 64)
|
| 419 |
+
)
|
| 420 |
+
dev = torch.device("cuda" if cfg.device == "auto" else cfg.device) if use_cuda else None
|
| 421 |
+
|
| 422 |
+
chunks: list[bytes] = []
|
| 423 |
+
total_sse = 0.0
|
| 424 |
+
for start in range(0, n_blocks, chunk_blocks):
|
| 425 |
+
stop = min(start + chunk_blocks, n_blocks)
|
| 426 |
+
Xb = X[start:stop]
|
| 427 |
+
sig2 = np.mean(Xb * Xb, axis=1, keepdims=True)
|
| 428 |
+
if W_raw is None:
|
| 429 |
+
Wb = np.sqrt(sig2 + Xb * Xb)
|
| 430 |
+
else:
|
| 431 |
+
wr = W_raw[start:stop]
|
| 432 |
+
Wb = np.sqrt(np.maximum(wr, 1.0e-6)) * np.sqrt(sig2 + Xb * Xb) if cfg.temper_imatrix else wr
|
| 433 |
+
wm = np.mean(Wb, axis=1, keepdims=True)
|
| 434 |
+
Wb = np.where(wm > 1.0e-30, Wb / np.maximum(wm, 1.0e-30), 1.0).astype(np.float32)
|
| 435 |
+
|
| 436 |
+
if use_cuda and dev is not None:
|
| 437 |
+
raw_b, sse_b = _quantize_q4_0_hpc_cuda(Xb, Wb, dev, cfg)
|
| 438 |
+
else:
|
| 439 |
+
raw_b, sse_b = _quantize_q4_0_hpc_cpu(Xb, Wb, cfg)
|
| 440 |
+
chunks.append(raw_b)
|
| 441 |
+
total_sse += sse_b
|
| 442 |
+
|
| 443 |
+
rmse = float(np.sqrt(total_sse / x.size))
|
| 444 |
+
return b"".join(chunks), n_blocks, rmse
|