CompressedGemma commited on
Commit
279a216
·
verified ·
1 Parent(s): 12a5d5a

Upload 6 files

Browse files
Files changed (6) hide show
  1. __init__.py +7 -0
  2. __main__.py +8 -10
  3. config.py +4 -4
  4. gguf.py +116 -93
  5. gui.py +67 -70
  6. q3_k.py +715 -0
__init__.py CHANGED
@@ -26,6 +26,7 @@ from .gguf import (
26
  expand_importance,
27
  is_q1_0_eligible,
28
  is_q2k_eligible,
 
29
  is_q4_0_eligible,
30
  lookup_imatrix,
31
  read_imatrix,
@@ -34,6 +35,7 @@ from .gguf import (
34
  from .pipeline import Q2KQuantizer, QuantizedTensor, TensorStats
35
  from .q1_0 import Q1_0_BLOCK_BYTES, QK1_0, dequantize_q1_0_bytes, quantize_tensor_q1_0
36
  from .q2k import Q2KBlock, QK_K, dequantize_params, pack_codes, unpack_codes
 
37
  from .q4_0 import QK4_0, dequantize_q4_0_bytes, quantize_tensor_q4_0
38
 
39
  __all__ = [
@@ -60,6 +62,7 @@ __all__ = [
60
  "expand_importance",
61
  "is_q1_0_eligible",
62
  "is_q2k_eligible",
 
63
  "is_q4_0_eligible",
64
  "lookup_imatrix",
65
  "read_imatrix",
@@ -68,6 +71,10 @@ __all__ = [
68
  "Q1_0_BLOCK_BYTES",
69
  "dequantize_q1_0_bytes",
70
  "quantize_tensor_q1_0",
 
 
 
 
71
  "QK4_0",
72
  "dequantize_q4_0_bytes",
73
  "quantize_tensor_q4_0",
 
26
  expand_importance,
27
  is_q1_0_eligible,
28
  is_q2k_eligible,
29
+ is_q3_k_eligible,
30
  is_q4_0_eligible,
31
  lookup_imatrix,
32
  read_imatrix,
 
35
  from .pipeline import Q2KQuantizer, QuantizedTensor, TensorStats
36
  from .q1_0 import Q1_0_BLOCK_BYTES, QK1_0, dequantize_q1_0_bytes, quantize_tensor_q1_0
37
  from .q2k import Q2KBlock, QK_K, dequantize_params, pack_codes, unpack_codes
38
+ from .q3_k import Q3_K_BLOCK_BYTES, QK3_K, dequantize_q3_k_bytes, quantize_tensor_q3_k
39
  from .q4_0 import QK4_0, dequantize_q4_0_bytes, quantize_tensor_q4_0
40
 
41
  __all__ = [
 
62
  "expand_importance",
63
  "is_q1_0_eligible",
64
  "is_q2k_eligible",
65
+ "is_q3_k_eligible",
66
  "is_q4_0_eligible",
67
  "lookup_imatrix",
68
  "read_imatrix",
 
71
  "Q1_0_BLOCK_BYTES",
72
  "dequantize_q1_0_bytes",
73
  "quantize_tensor_q1_0",
74
+ "QK3_K",
75
+ "Q3_K_BLOCK_BYTES",
76
+ "dequantize_q3_k_bytes",
77
+ "quantize_tensor_q3_k",
78
  "QK4_0",
79
  "dequantize_q4_0_bytes",
80
  "quantize_tensor_q4_0",
__main__.py CHANGED
@@ -22,7 +22,6 @@ from .config import HPCConfig
22
  from .factored import factor_only_solve
23
  from .gguf import (
24
  GGUFReader,
25
- SUPPORTED_READ_TYPES,
26
  expand_importance,
27
  is_q2k_eligible,
28
  lookup_imatrix,
@@ -56,7 +55,7 @@ def _config_from_args(args) -> HPCConfig:
56
  cfg.promote_attn_q4 = True
57
  if args.format is not None:
58
  cfg.quant_format = args.format
59
- if args.format == "q2_k":
60
  cfg.enable_q4_fallback = False
61
  if getattr(args, "tensor_type", None):
62
  custom: dict[str, str] = {}
@@ -69,6 +68,7 @@ def _config_from_args(args) -> HPCConfig:
69
  canonical = {
70
  "q1_0": "Q1_0",
71
  "q2_k": "Q2_K",
 
72
  "q4_0": "Q4_0",
73
  "copy": "Copy",
74
  "auto": "Auto",
@@ -77,7 +77,7 @@ def _config_from_args(args) -> HPCConfig:
77
  if norm is None:
78
  raise SystemExit(
79
  f"--tensor-type {key!r} has invalid quant {value!r}; "
80
- "use Q1_0, Q2_K, Q4_0, Copy, or Auto"
81
  )
82
  custom[key] = norm
83
  cfg.custom_quant_map = custom
@@ -127,8 +127,6 @@ def _run_gguf(args, cfg: HPCConfig) -> None:
127
  source_type=ti.type,
128
  custom_quant_map=cfg.custom_quant_map or None,
129
  )
130
- if tgt is not None and ti.type not in SUPPORTED_READ_TYPES:
131
- tgt = None
132
  tag = tgt if tgt else "COPY"
133
  print(
134
  f" {tag:4s} {ti.name:48s} {ti.type_name:6s} "
@@ -155,8 +153,8 @@ def _run_gguf(args, cfg: HPCConfig) -> None:
155
  verbose=True,
156
  )
157
  print(
158
- f"wrote {args.output}: {int(stats.get('q2_k', 0))} Q2_K + {int(stats.get('q4_0', 0))} Q4_0 + "
159
- f"{int(stats.get('q1_0', 0))} Q1_0 "
160
  f"({int(stats['quantized'])}/{int(stats['tensors'])} tensors), rmse={stats['rmse']:.6e}"
161
  )
162
  return
@@ -281,9 +279,9 @@ def main() -> None:
281
  parser.add_argument("--no-spectral", action="store_true", help="disable spectral/DC objective")
282
  parser.add_argument(
283
  "--format",
284
- choices=("mixed", "mixed_q1", "custom", "q1_0", "q4_0", "q2_k"),
285
  default=None,
286
- help="quantization format mode: mixed (Q2_K+Q4_0), mixed_q1 (Q1_0+Q4_0), custom (per-tensor-type overrides), q1_0 (pure Q1_0), q4_0 (pure Q4_0), or q2_k (pure Q2_K)",
287
  )
288
  parser.add_argument(
289
  "--tensor-type",
@@ -291,7 +289,7 @@ def main() -> None:
291
  default=[],
292
  metavar="TYPE=QUANT",
293
  help="per-tensor-type override, e.g. ffn_up=Q1_0 or attn_output=Q1_0 "
294
- "(QUANT: Q1_0, Q2_K, Q4_0, Copy, Auto; repeatable)",
295
  )
296
  parser.add_argument("--no-q4-fallback", action="store_true", help="disable Q4_0 fallback for non-256-aligned tensors")
297
  parser.add_argument("--keep-embd", action="store_true", help="keep token_embd/output.weight at source precision")
 
22
  from .factored import factor_only_solve
23
  from .gguf import (
24
  GGUFReader,
 
25
  expand_importance,
26
  is_q2k_eligible,
27
  lookup_imatrix,
 
55
  cfg.promote_attn_q4 = True
56
  if args.format is not None:
57
  cfg.quant_format = args.format
58
+ if args.format in ("q2_k", "q3_k"):
59
  cfg.enable_q4_fallback = False
60
  if getattr(args, "tensor_type", None):
61
  custom: dict[str, str] = {}
 
68
  canonical = {
69
  "q1_0": "Q1_0",
70
  "q2_k": "Q2_K",
71
+ "q3_k": "Q3_K",
72
  "q4_0": "Q4_0",
73
  "copy": "Copy",
74
  "auto": "Auto",
 
77
  if norm is None:
78
  raise SystemExit(
79
  f"--tensor-type {key!r} has invalid quant {value!r}; "
80
+ "use Q1_0, Q2_K, Q3_K, Q4_0, Copy, or Auto"
81
  )
82
  custom[key] = norm
83
  cfg.custom_quant_map = custom
 
127
  source_type=ti.type,
128
  custom_quant_map=cfg.custom_quant_map or None,
129
  )
 
 
130
  tag = tgt if tgt else "COPY"
131
  print(
132
  f" {tag:4s} {ti.name:48s} {ti.type_name:6s} "
 
153
  verbose=True,
154
  )
155
  print(
156
+ f"wrote {args.output}: {int(stats.get('q2_k', 0))} Q2_K + {int(stats.get('q3_k', 0))} Q3_K + "
157
+ f"{int(stats.get('q4_0', 0))} Q4_0 + {int(stats.get('q1_0', 0))} Q1_0 "
158
  f"({int(stats['quantized'])}/{int(stats['tensors'])} tensors), rmse={stats['rmse']:.6e}"
159
  )
160
  return
 
279
  parser.add_argument("--no-spectral", action="store_true", help="disable spectral/DC objective")
280
  parser.add_argument(
281
  "--format",
282
+ choices=("mixed", "mixed_q1", "custom", "q1_0", "q3_k", "q4_0", "q2_k"),
283
  default=None,
284
+ help="quantization format mode: mixed (Q2_K+Q4_0), mixed_q1 (Q1_0+Q4_0), custom (per-tensor-type overrides), q1_0 (pure Q1_0), q3_k (pure Q3_K), q4_0 (pure Q4_0), or q2_k (pure Q2_K)",
285
  )
286
  parser.add_argument(
287
  "--tensor-type",
 
289
  default=[],
290
  metavar="TYPE=QUANT",
291
  help="per-tensor-type override, e.g. ffn_up=Q1_0 or attn_output=Q1_0 "
292
+ "(QUANT: Q1_0, Q2_K, Q3_K, Q4_0, Copy, Auto; repeatable)",
293
  )
294
  parser.add_argument("--no-q4-fallback", action="store_true", help="disable Q4_0 fallback for non-256-aligned tensors")
295
  parser.add_argument("--keep-embd", action="store_true", help="keep token_embd/output.weight at source precision")
config.py CHANGED
@@ -121,15 +121,15 @@ class HPCConfig:
121
  raise ValueError("workers must be >= 0 (0 = auto CPU count)")
122
  if self.device not in ("auto", "cuda", "cpu") and not self.device.startswith("cuda:"):
123
  raise ValueError("device must be 'auto', 'cuda', 'cuda:N', or 'cpu'")
124
- if self.quant_format not in ("mixed", "mixed_q1", "custom", "q1_0", "q4_0", "q2_k"):
125
  raise ValueError(
126
- "quant_format must be 'mixed', 'mixed_q1', 'custom', 'q1_0', 'q4_0', or 'q2_k'"
127
  )
128
- allowed_custom = {"q1_0", "q2_k", "q4_0", "copy", "auto"}
129
  for tensor_type, quant in self.custom_quant_map.items():
130
  if str(quant).strip().lower() not in allowed_custom:
131
  raise ValueError(
132
  f"custom_quant_map[{tensor_type!r}] must be one of "
133
- f"Q1_0, Q2_K, Q4_0, Copy, Auto, got {quant!r}"
134
  )
135
  return self
 
121
  raise ValueError("workers must be >= 0 (0 = auto CPU count)")
122
  if self.device not in ("auto", "cuda", "cpu") and not self.device.startswith("cuda:"):
123
  raise ValueError("device must be 'auto', 'cuda', 'cuda:N', or 'cpu'")
124
+ if self.quant_format not in ("mixed", "mixed_q1", "custom", "q1_0", "q3_k", "q4_0", "q2_k"):
125
  raise ValueError(
126
+ "quant_format must be 'mixed', 'mixed_q1', 'custom', 'q1_0', 'q3_k', 'q4_0', or 'q2_k'"
127
  )
128
+ allowed_custom = {"q1_0", "q2_k", "q3_k", "q4_0", "copy", "auto"}
129
  for tensor_type, quant in self.custom_quant_map.items():
130
  if str(quant).strip().lower() not in allowed_custom:
131
  raise ValueError(
132
  f"custom_quant_map[{tensor_type!r}] must be one of "
133
+ f"Q1_0, Q2_K, Q3_K, Q4_0, Copy, Auto, got {quant!r}"
134
  )
135
  return self
gguf.py CHANGED
@@ -23,6 +23,7 @@ from pathlib import Path
23
  import numpy as np
24
 
25
  from .q2k import QK_K, blocks_to_bytes, dequantize_params_batch, unpack_codes
 
26
  from .q4_0 import Q4_0_BLOCK_BYTES, QK4_0, quantize_tensor_q4_0
27
  from .q1_0 import QK1_0, Q1_0_BLOCK_BYTES, quantize_tensor_q1_0
28
 
@@ -37,6 +38,7 @@ GGML_TYPE_Q5_0 = 6
37
  GGML_TYPE_Q5_1 = 7
38
  GGML_TYPE_Q8_0 = 8
39
  GGML_TYPE_Q2_K = 10
 
40
  GGML_TYPE_BF16 = 30
41
  GGML_TYPE_Q1_0 = 41
42
 
@@ -49,21 +51,9 @@ TYPE_NAME = {
49
  GGML_TYPE_Q5_1: "Q5_1",
50
  GGML_TYPE_Q8_0: "Q8_0",
51
  GGML_TYPE_Q2_K: "Q2_K",
 
52
  GGML_TYPE_BF16: "BF16",
53
  GGML_TYPE_Q1_0: "Q1_0",
54
- 11: "Q3_K",
55
- 12: "Q4_K",
56
- 13: "Q5_K",
57
- 14: "Q6_K",
58
- 15: "Q8_K",
59
- 16: "IQ2_XXS",
60
- 17: "IQ2_XS",
61
- 18: "IQ3_XXS",
62
- 19: "IQ1_S",
63
- 20: "IQ4_NL",
64
- 21: "IQ3_S",
65
- 22: "IQ2_S",
66
- 23: "IQ4_XS",
67
  }
68
 
69
  BLOCK_SIZE = {
@@ -76,12 +66,8 @@ BLOCK_SIZE = {
76
  GGML_TYPE_Q5_1: 32,
77
  GGML_TYPE_Q8_0: 32,
78
  GGML_TYPE_Q2_K: QK_K,
 
79
  GGML_TYPE_Q1_0: QK1_0,
80
- 11: QK_K, # Q3_K
81
- 12: QK_K, # Q4_K
82
- 13: QK_K, # Q5_K
83
- 14: QK_K, # Q6_K
84
- 15: QK_K, # Q8_K
85
  }
86
  BLOCK_BYTES = {
87
  GGML_TYPE_F32: 4,
@@ -93,12 +79,8 @@ BLOCK_BYTES = {
93
  GGML_TYPE_Q5_1: 24,
94
  GGML_TYPE_Q8_0: 34,
95
  GGML_TYPE_Q2_K: 84,
 
96
  GGML_TYPE_Q1_0: Q1_0_BLOCK_BYTES,
97
- 11: 110, # Q3_K
98
- 12: 144, # Q4_K
99
- 13: 176, # Q5_K
100
- 14: 210, # Q6_K
101
- 15: 292, # Q8_K
102
  }
103
  TYPE_BPW = {
104
  GGML_TYPE_F32: 32.0,
@@ -110,8 +92,8 @@ TYPE_BPW = {
110
  GGML_TYPE_Q4_1: 5.0,
111
  GGML_TYPE_Q4_0: 4.5,
112
  GGML_TYPE_Q2_K: 2.625,
 
113
  GGML_TYPE_Q1_0: 1.125,
114
- 11: 3.4375, # Q3_K
115
  12: 4.5, # Q4_K
116
  13: 5.5, # Q5_K
117
  14: 6.5625, # Q6_K
@@ -140,6 +122,7 @@ SUPPORTED_READ_TYPES = {
140
  GGML_TYPE_Q4_0,
141
  GGML_TYPE_Q8_0,
142
  GGML_TYPE_Q2_K,
 
143
  GGML_TYPE_Q1_0,
144
  }
145
 
@@ -150,7 +133,6 @@ class TensorInfo:
150
  dims: tuple[int, ...]
151
  type: int
152
  offset: int
153
- raw_size: int | None = None
154
 
155
  @property
156
  def n_elements(self) -> int:
@@ -169,8 +151,6 @@ class TensorInfo:
169
 
170
  @property
171
  def n_bytes(self) -> int:
172
- if self.raw_size is not None:
173
- return self.raw_size
174
  if self.type not in BLOCK_SIZE:
175
  raise ValueError(f"unsupported GGUF type {self.type} ({self.type_name})")
176
  block = BLOCK_SIZE[self.type]
@@ -260,18 +240,6 @@ class GGUFReader:
260
  self.info_end = f.tell()
261
  self.alignment = int(self.metadata.get("general.alignment", DEFAULT_ALIGNMENT))
262
  self.data_start = _align(self.info_end, self.alignment)
263
- file_size = self.path.stat().st_size
264
- for i, ti in enumerate(self.tensors):
265
- if ti.type in BLOCK_SIZE:
266
- continue
267
- end = (
268
- self.tensors[i + 1].offset
269
- if i + 1 < len(self.tensors)
270
- else file_size - self.data_start
271
- )
272
- if end < ti.offset:
273
- raise ValueError(f"{self.path}: tensor '{ti.name}' has an invalid offset")
274
- ti.raw_size = end - ti.offset
275
  self._by_name = {ti.name: ti for ti in self.tensors}
276
 
277
  def info(self, name: str) -> TensorInfo:
@@ -360,6 +328,9 @@ def _dequantize(raw: bytes, ti: TensorInfo) -> np.ndarray:
360
  d = blocks[:, :2].copy().view("<f2").reshape(-1, 1).astype(np.float32)
361
  bits = np.unpackbits(blocks[:, 2:], axis=1, bitorder="little")[:, :QK1_0].astype(np.float32)
362
  return (d * (bits * 2.0 - 1.0)).reshape(-1)
 
 
 
363
  if t == GGML_TYPE_Q2_K:
364
  blocks = np.frombuffer(raw, dtype=np.uint8).reshape(-1, 84)
365
  n = blocks.shape[0]
@@ -538,6 +509,20 @@ def is_q2k_eligible(name: str, dims: tuple[int, ...]) -> bool:
538
  return n_elements >= QK_K and n_elements % QK_K == 0
539
 
540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
541
  def is_q4_0_eligible(
542
  name: str,
543
  dims: tuple[int, ...],
@@ -603,10 +588,11 @@ def target_quant_type(
603
  tensor types fall back to the 'mixed' plan.
604
  * 'q4_0': all 32-aligned eligible weight tensors -> Q4_0.
605
  * 'q2_k': only Q2_K-eligible tensors -> Q2_K; everything else copied.
 
606
  * 'q1_0': all 128-aligned eligible weight tensors -> Q1_0.
607
 
608
  ``custom_quant_map`` maps a layer-independent tensor type (see
609
- :func:`tensor_type_key`) to 'Q1_0', 'Q2_K', 'Q4_0', 'Copy', or 'Auto'.
610
  Non-Auto entries override the selected mode for that tensor type. A target
611
  is applied only when the tensor is actually eligible for it; explicit
612
  'Copy' (and ineligible targets) leave the tensor at its source precision.
@@ -627,6 +613,9 @@ def target_quant_type(
627
  elif choice == "Q2_K":
628
  if is_q2k_eligible(name, dims):
629
  tgt = "Q2_K"
 
 
 
630
  elif choice == "Q4_0":
631
  if is_q4_0_eligible(name, dims, include_embd=True, allow_q2k_tensors=True):
632
  tgt = "Q4_0"
@@ -668,6 +657,9 @@ def target_quant_type(
668
  elif fmt == "q2_k":
669
  if is_q2k_eligible(name, dims):
670
  tgt = "Q2_K"
 
 
 
671
  else:
672
  if promote_attn_q4 and _is_attention_projection(name) and is_q4_0_eligible(
673
  name, dims, include_embd=quantize_embd_q4, promote_attn=True
@@ -682,7 +674,7 @@ def target_quant_type(
682
 
683
  if tgt is not None and source_type is not None:
684
  src_bpw = source_type_bpw(int(source_type))
685
- tgt_bpw = {"Q2_K": 2.625, "Q4_0": 4.5, "Q1_0": 1.125}[tgt]
686
  if src_bpw <= tgt_bpw + 1.0e-6:
687
  return None
688
  return tgt
@@ -750,7 +742,7 @@ def write_quantized_gguf(
750
  custom_choice is not None
751
  and str(custom_choice).strip().lower() not in ("", "auto")
752
  )
753
- if target_fmt is None and not explicit_custom:
754
  src_bpw = source_type_bpw(ti.type)
755
  if q_format == "q1_0" and len(ti.dims) >= 2 and ti.dims[0] % QK1_0 == 0 and src_bpw > 1.125:
756
  target_fmt = "Q1_0"
@@ -792,6 +784,11 @@ def write_quantized_gguf(
792
  out_type = GGML_TYPE_Q2_K
793
  out_size = n_blocks * 84
794
  total_planned_blocks += n_blocks
 
 
 
 
 
795
  elif fmt == "Q4_0":
796
  n_blocks = ti.n_elements // QK4_0
797
  out_type = GGML_TYPE_Q4_0
@@ -809,9 +806,10 @@ def write_quantized_gguf(
809
  data_offset = _align(data_offset + out_size, alignment)
810
 
811
  has_q2k = any(fmt == "Q2_K" for fmt in plan)
 
812
  has_q1_0 = any(fmt == "Q1_0" for fmt in plan)
813
- # 10 = MOSTLY_Q2_K, 2 = MOSTLY_Q4_0, 40 = MOSTLY_Q1_0
814
- ftype_code = 10 if has_q2k else (40 if has_q1_0 else 2)
815
  kv_pairs = []
816
  for key, vtype, raw in reader.kv_pairs:
817
  if quantized_count and key == "general.file_type" and vtype == 4:
@@ -825,6 +823,7 @@ def write_quantized_gguf(
825
  total_rmse = 0.0
826
  total_quantized = 0
827
  total_q2k = 0
 
828
  total_q4_0 = 0
829
  total_q1_0 = 0
830
  total_elements = 0
@@ -937,6 +936,78 @@ def write_quantized_gguf(
937
  float(res.stats.rmse),
938
  imp is not None,
939
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
940
  elif fmt == "Q4_0":
941
  t_blocks_q4 = ti.n_elements // QK4_0
942
  eff_tb = max(1, t_blocks_q4 // 8)
@@ -1105,57 +1176,9 @@ def write_quantized_gguf(
1105
  "tensors": float(len(out_infos)),
1106
  "quantized": float(total_quantized),
1107
  "q2_k": float(total_q2k),
 
1108
  "q4_0": float(total_q4_0),
1109
  "q1_0": float(total_q1_0),
1110
  "elements": float(total_elements),
1111
  "rmse": rmse,
1112
  }
1113
-
1114
-
1115
- def estimate_gguf_size(
1116
- reader: GGUFReader,
1117
- *,
1118
- enable_q4_fallback: bool = True,
1119
- quantize_embd_q4: bool = True,
1120
- promote_attn_q4: bool = False,
1121
- quant_format: str = "mixed",
1122
- custom_quant_map: dict[str, str] | None = None,
1123
- ) -> int:
1124
- """Return the projected byte size of a full-model quantized GGUF."""
1125
- plan: list[tuple[TensorInfo, str | None]] = []
1126
- for ti in reader.tensors:
1127
- tgt = target_quant_type(
1128
- ti.name,
1129
- ti.dims,
1130
- enable_q4_fallback=enable_q4_fallback,
1131
- quantize_embd_q4=quantize_embd_q4,
1132
- promote_attn_q4=promote_attn_q4,
1133
- quant_format=quant_format,
1134
- source_type=ti.type,
1135
- custom_quant_map=custom_quant_map,
1136
- )
1137
- if tgt is not None and ti.type not in SUPPORTED_READ_TYPES:
1138
- tgt = None
1139
- plan.append((ti, tgt))
1140
-
1141
- header = 24
1142
- for key, _vtype, raw in reader.kv_pairs:
1143
- header += 8 + len(key.encode("utf-8")) + 4 + len(raw)
1144
- for ti, _tgt in plan:
1145
- header += 8 + len(ti.name.encode("utf-8")) + 4 + 8 * len(ti.dims) + 4 + 8
1146
- data_start = _align(header, reader.alignment)
1147
-
1148
- offset = 0
1149
- final_end = data_start
1150
- for ti, tgt in plan:
1151
- if tgt == "Q2_K":
1152
- out_size = (ti.n_elements // QK_K) * 84
1153
- elif tgt == "Q4_0":
1154
- out_size = (ti.n_elements // QK4_0) * Q4_0_BLOCK_BYTES
1155
- elif tgt == "Q1_0":
1156
- out_size = (ti.n_elements // QK1_0) * Q1_0_BLOCK_BYTES
1157
- else:
1158
- out_size = ti.n_bytes
1159
- final_end = data_start + offset + out_size
1160
- offset = _align(offset + out_size, reader.alignment)
1161
- return final_end
 
23
  import numpy as np
24
 
25
  from .q2k import QK_K, blocks_to_bytes, dequantize_params_batch, unpack_codes
26
+ from .q3_k import Q3_K_BLOCK_BYTES, QK3_K, dequantize_q3_k_bytes, quantize_tensor_q3_k
27
  from .q4_0 import Q4_0_BLOCK_BYTES, QK4_0, quantize_tensor_q4_0
28
  from .q1_0 import QK1_0, Q1_0_BLOCK_BYTES, quantize_tensor_q1_0
29
 
 
38
  GGML_TYPE_Q5_1 = 7
39
  GGML_TYPE_Q8_0 = 8
40
  GGML_TYPE_Q2_K = 10
41
+ GGML_TYPE_Q3_K = 11
42
  GGML_TYPE_BF16 = 30
43
  GGML_TYPE_Q1_0 = 41
44
 
 
51
  GGML_TYPE_Q5_1: "Q5_1",
52
  GGML_TYPE_Q8_0: "Q8_0",
53
  GGML_TYPE_Q2_K: "Q2_K",
54
+ GGML_TYPE_Q3_K: "Q3_K",
55
  GGML_TYPE_BF16: "BF16",
56
  GGML_TYPE_Q1_0: "Q1_0",
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  }
58
 
59
  BLOCK_SIZE = {
 
66
  GGML_TYPE_Q5_1: 32,
67
  GGML_TYPE_Q8_0: 32,
68
  GGML_TYPE_Q2_K: QK_K,
69
+ GGML_TYPE_Q3_K: QK3_K,
70
  GGML_TYPE_Q1_0: QK1_0,
 
 
 
 
 
71
  }
72
  BLOCK_BYTES = {
73
  GGML_TYPE_F32: 4,
 
79
  GGML_TYPE_Q5_1: 24,
80
  GGML_TYPE_Q8_0: 34,
81
  GGML_TYPE_Q2_K: 84,
82
+ GGML_TYPE_Q3_K: Q3_K_BLOCK_BYTES,
83
  GGML_TYPE_Q1_0: Q1_0_BLOCK_BYTES,
 
 
 
 
 
84
  }
85
  TYPE_BPW = {
86
  GGML_TYPE_F32: 32.0,
 
92
  GGML_TYPE_Q4_1: 5.0,
93
  GGML_TYPE_Q4_0: 4.5,
94
  GGML_TYPE_Q2_K: 2.625,
95
+ GGML_TYPE_Q3_K: 3.4375,
96
  GGML_TYPE_Q1_0: 1.125,
 
97
  12: 4.5, # Q4_K
98
  13: 5.5, # Q5_K
99
  14: 6.5625, # Q6_K
 
122
  GGML_TYPE_Q4_0,
123
  GGML_TYPE_Q8_0,
124
  GGML_TYPE_Q2_K,
125
+ GGML_TYPE_Q3_K,
126
  GGML_TYPE_Q1_0,
127
  }
128
 
 
133
  dims: tuple[int, ...]
134
  type: int
135
  offset: int
 
136
 
137
  @property
138
  def n_elements(self) -> int:
 
151
 
152
  @property
153
  def n_bytes(self) -> int:
 
 
154
  if self.type not in BLOCK_SIZE:
155
  raise ValueError(f"unsupported GGUF type {self.type} ({self.type_name})")
156
  block = BLOCK_SIZE[self.type]
 
240
  self.info_end = f.tell()
241
  self.alignment = int(self.metadata.get("general.alignment", DEFAULT_ALIGNMENT))
242
  self.data_start = _align(self.info_end, self.alignment)
 
 
 
 
 
 
 
 
 
 
 
 
243
  self._by_name = {ti.name: ti for ti in self.tensors}
244
 
245
  def info(self, name: str) -> TensorInfo:
 
328
  d = blocks[:, :2].copy().view("<f2").reshape(-1, 1).astype(np.float32)
329
  bits = np.unpackbits(blocks[:, 2:], axis=1, bitorder="little")[:, :QK1_0].astype(np.float32)
330
  return (d * (bits * 2.0 - 1.0)).reshape(-1)
331
+ if t == GGML_TYPE_Q3_K:
332
+ n_blocks = len(raw) // Q3_K_BLOCK_BYTES
333
+ return dequantize_q3_k_bytes(raw, n_blocks)
334
  if t == GGML_TYPE_Q2_K:
335
  blocks = np.frombuffer(raw, dtype=np.uint8).reshape(-1, 84)
336
  n = blocks.shape[0]
 
509
  return n_elements >= QK_K and n_elements % QK_K == 0
510
 
511
 
512
+ def is_q3_k_eligible(name: str, dims: tuple[int, ...]) -> bool:
513
+ """True for 256-aligned 2D/3D weight tensors eligible for Q3_K."""
514
+ if _is_skipped_metadata_tensor(name, dims):
515
+ return False
516
+ if _is_embd_or_head(name):
517
+ return False
518
+ if dims[0] % QK3_K != 0:
519
+ return False
520
+ n_elements = 1
521
+ for d in dims:
522
+ n_elements *= int(d)
523
+ return n_elements >= QK3_K and n_elements % QK3_K == 0
524
+
525
+
526
  def is_q4_0_eligible(
527
  name: str,
528
  dims: tuple[int, ...],
 
588
  tensor types fall back to the 'mixed' plan.
589
  * 'q4_0': all 32-aligned eligible weight tensors -> Q4_0.
590
  * 'q2_k': only Q2_K-eligible tensors -> Q2_K; everything else copied.
591
+ * 'q3_k': only Q3_K-eligible tensors -> Q3_K; everything else copied.
592
  * 'q1_0': all 128-aligned eligible weight tensors -> Q1_0.
593
 
594
  ``custom_quant_map`` maps a layer-independent tensor type (see
595
+ :func:`tensor_type_key`) to 'Q1_0', 'Q2_K', 'Q3_K', 'Q4_0', 'Copy', or 'Auto'.
596
  Non-Auto entries override the selected mode for that tensor type. A target
597
  is applied only when the tensor is actually eligible for it; explicit
598
  'Copy' (and ineligible targets) leave the tensor at its source precision.
 
613
  elif choice == "Q2_K":
614
  if is_q2k_eligible(name, dims):
615
  tgt = "Q2_K"
616
+ elif choice == "Q3_K":
617
+ if is_q3_k_eligible(name, dims):
618
+ tgt = "Q3_K"
619
  elif choice == "Q4_0":
620
  if is_q4_0_eligible(name, dims, include_embd=True, allow_q2k_tensors=True):
621
  tgt = "Q4_0"
 
657
  elif fmt == "q2_k":
658
  if is_q2k_eligible(name, dims):
659
  tgt = "Q2_K"
660
+ elif fmt == "q3_k":
661
+ if is_q3_k_eligible(name, dims):
662
+ tgt = "Q3_K"
663
  else:
664
  if promote_attn_q4 and _is_attention_projection(name) and is_q4_0_eligible(
665
  name, dims, include_embd=quantize_embd_q4, promote_attn=True
 
674
 
675
  if tgt is not None and source_type is not None:
676
  src_bpw = source_type_bpw(int(source_type))
677
+ tgt_bpw = {"Q2_K": 2.625, "Q3_K": 3.4375, "Q4_0": 4.5, "Q1_0": 1.125}[tgt]
678
  if src_bpw <= tgt_bpw + 1.0e-6:
679
  return None
680
  return tgt
 
742
  custom_choice is not None
743
  and str(custom_choice).strip().lower() not in ("", "auto")
744
  )
745
+ if target_fmt is None and not explicit_custom and q_format != "q3_k":
746
  src_bpw = source_type_bpw(ti.type)
747
  if q_format == "q1_0" and len(ti.dims) >= 2 and ti.dims[0] % QK1_0 == 0 and src_bpw > 1.125:
748
  target_fmt = "Q1_0"
 
784
  out_type = GGML_TYPE_Q2_K
785
  out_size = n_blocks * 84
786
  total_planned_blocks += n_blocks
787
+ elif fmt == "Q3_K":
788
+ n_blocks = ti.n_elements // QK3_K
789
+ out_type = GGML_TYPE_Q3_K
790
+ out_size = n_blocks * Q3_K_BLOCK_BYTES
791
+ total_planned_blocks += max(1, n_blocks // 16)
792
  elif fmt == "Q4_0":
793
  n_blocks = ti.n_elements // QK4_0
794
  out_type = GGML_TYPE_Q4_0
 
806
  data_offset = _align(data_offset + out_size, alignment)
807
 
808
  has_q2k = any(fmt == "Q2_K" for fmt in plan)
809
+ has_q3k = any(fmt == "Q3_K" for fmt in plan)
810
  has_q1_0 = any(fmt == "Q1_0" for fmt in plan)
811
+ # 11 = MOSTLY_Q3_K, 10 = MOSTLY_Q2_K, 2 = MOSTLY_Q4_0, 40 = MOSTLY_Q1_0
812
+ ftype_code = 11 if has_q3k else (10 if has_q2k else (40 if has_q1_0 else 2))
813
  kv_pairs = []
814
  for key, vtype, raw in reader.kv_pairs:
815
  if quantized_count and key == "general.file_type" and vtype == 4:
 
823
  total_rmse = 0.0
824
  total_quantized = 0
825
  total_q2k = 0
826
+ total_q3k = 0
827
  total_q4_0 = 0
828
  total_q1_0 = 0
829
  total_elements = 0
 
936
  float(res.stats.rmse),
937
  imp is not None,
938
  )
939
+ elif fmt == "Q3_K":
940
+ t_blocks_q3 = ti.n_elements // QK3_K
941
+ eff_tb = max(1, t_blocks_q3 // 16)
942
+ raw_imp = lookup_imatrix(imat, ti.name) if imat is not None else None
943
+ has_imat = raw_imp is not None and raw_imp.size == ti.row_width
944
+ written_bytes = 0
945
+ sse_q3 = 0.0
946
+ done_q3_blks = 0
947
+ t_q3_start = time.time()
948
+
949
+ for x_chunk, row, _r0, _r1 in reader.iter_tensor_row_chunks(ti.name, max_elements=8_388_608):
950
+ if stop_event is not None and stop_event.is_set():
951
+ raise InterruptedError("Quantization cancelled by user")
952
+ imp_chunk = expand_importance(raw_imp, x_chunk.size, row) if has_imat else None
953
+ q3_bytes, nb_chunk, chunk_rmse = quantize_tensor_q3_k(
954
+ x_chunk, importance=imp_chunk, cfg=cfg
955
+ )
956
+ fout.write(q3_bytes)
957
+ written_bytes += len(q3_bytes)
958
+ sse_q3 += (chunk_rmse * chunk_rmse) * x_chunk.size
959
+ done_q3_blks += nb_chunk
960
+ if stage_callback is not None:
961
+ frac = done_q3_blks / max(t_blocks_q3, 1)
962
+ eff_blocks = completed_planned_blocks + frac * eff_tb
963
+ elapsed_model = max(time.time() - model_t0, 1.0e-6)
964
+ model_rate = eff_blocks / elapsed_model
965
+ model_eta = max(total_planned_blocks - eff_blocks, 0.0) / max(model_rate, 1.0e-6)
966
+ el_q3 = max(time.time() - t_q3_start, 1.0e-6)
967
+ r_q3 = done_q3_blks / el_q3
968
+ eta_q3 = (t_blocks_q3 - done_q3_blks) / max(r_q3, 1.0e-6)
969
+ stage_callback(
970
+ idx + 1,
971
+ len(out_infos),
972
+ ti,
973
+ {
974
+ "phase": "Q3_K: Analog + WLS + Sieve/Viterbi + FP16-ULP Quantization",
975
+ "done": done_q3_blks,
976
+ "total": t_blocks_q3,
977
+ "detail": f"blk {done_q3_blks:,}/{t_blocks_q3:,} ({r_q3:.0f} blk/s) rmse={chunk_rmse:.6e}",
978
+ "rate": r_q3,
979
+ "eta": eta_q3,
980
+ "rmse": chunk_rmse,
981
+ "sigma": float(np.sqrt(np.mean(x_chunk.astype(np.float64) ** 2))),
982
+ "model_pct": 100.0 * eff_blocks / max(total_planned_blocks, 1),
983
+ "model_eta": model_eta,
984
+ "model_done_blocks": int(eff_blocks),
985
+ "model_total_blocks": total_planned_blocks,
986
+ },
987
+ )
988
+
989
+ if written_bytes != out_size:
990
+ raise RuntimeError(f"{ti.name}: Q3_K payload size mismatch")
991
+ completed_planned_blocks += eff_tb
992
+ q3_rmse = float(np.sqrt(sse_q3 / ti.n_elements))
993
+ total_rmse += sse_q3
994
+ total_elements += ti.n_elements
995
+ total_quantized += 1
996
+ total_q3k += 1
997
+ if verbose:
998
+ print(
999
+ f" Q3_K {ti.name:48s} row={ti.row_width:6d} "
1000
+ f"rmse={q3_rmse:.6e} imatrix={'yes' if has_imat else 'no'}"
1001
+ )
1002
+ if progress_callback is not None:
1003
+ progress_callback(
1004
+ idx + 1,
1005
+ len(out_infos),
1006
+ ti.name,
1007
+ "Q3_K",
1008
+ q3_rmse,
1009
+ has_imat,
1010
+ )
1011
  elif fmt == "Q4_0":
1012
  t_blocks_q4 = ti.n_elements // QK4_0
1013
  eff_tb = max(1, t_blocks_q4 // 8)
 
1176
  "tensors": float(len(out_infos)),
1177
  "quantized": float(total_quantized),
1178
  "q2_k": float(total_q2k),
1179
+ "q3_k": float(total_q3k),
1180
  "q4_0": float(total_q4_0),
1181
  "q1_0": float(total_q1_0),
1182
  "elements": float(total_elements),
1183
  "rmse": rmse,
1184
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
gui.py CHANGED
@@ -49,23 +49,30 @@ if not (_HERE / "hpc_quantize_v2").is_dir() and (_HERE / "__init__.py").is_file(
49
  from hpc_quantize_v2 import (
50
  GGUFReader,
51
  HPCConfig,
 
52
  Q2KQuantizer,
 
 
 
 
 
53
  cuda_device_name,
54
  cuda_is_available,
55
  dequantize_q1_0_bytes,
 
56
  dequantize_q4_0_bytes,
57
  expand_importance,
58
  factor_only_solve,
59
  lookup_imatrix,
60
  quantize_tensor_q1_0,
 
61
  quantize_tensor_q4_0,
62
  read_imatrix,
63
  )
64
  from hpc_quantize_v2.gguf import (
65
- SUPPORTED_READ_TYPES,
66
- estimate_gguf_size,
67
  is_q1_0_eligible,
68
  is_q2k_eligible,
 
69
  is_q4_0_eligible,
70
  target_quant_type,
71
  tensor_type_key,
@@ -116,7 +123,7 @@ def _fmt_eta(seconds: float) -> str:
116
  class HPCQuantizeGUI:
117
  def __init__(self, root: tk.Tk) -> None:
118
  self.root = root
119
- self.root.title("HPC-Quantize V2 — Factored Q1_0 / Q2_K / Q4_0 & Geometry-Preserving Analog Engine")
120
  self.root.geometry("1260x900")
121
  self.root.minsize(1040, 740)
122
 
@@ -176,7 +183,6 @@ class HPCQuantizeGUI:
176
  self.sse_budget_var = tk.DoubleVar(value=0.0005)
177
 
178
  self.cli_preview_var = tk.StringVar()
179
- self.custom_size_var = tk.StringVar(value="Projected GGUF size: load a source GGUF")
180
  self.status_var = tk.StringVar(value="Ready.")
181
  self.model_progress_var = tk.DoubleVar(value=0.0)
182
  self.tensor_progress_var = tk.DoubleVar(value=0.0)
@@ -314,7 +320,7 @@ class HPCQuantizeGUI:
314
  mid.add(right_pane, weight=3)
315
 
316
  # Left: Engine & Factorization Options
317
- opt_frame = ttk.LabelFrame(left_pane, text="2. Factored Q1_0 / Q2_K / Q4_0 & Analog Controls", padding=8)
318
  opt_frame.pack(fill=tk.BOTH, expand=True, padx=(0, 6))
319
 
320
  mode_row = ttk.Frame(opt_frame)
@@ -335,6 +341,7 @@ class HPCQuantizeGUI:
335
  ("Mixed Q1_0 + Q4_0", "mixed_q1"),
336
  ("Pure Q1_0 (1.125 bpw)", "q1_0"),
337
  ("Pure Q2_K (2.625 bpw)", "q2_k"),
 
338
  ("Pure Q4_0 (4.500 bpw)", "q4_0"),
339
  ):
340
  ttk.Radiobutton(
@@ -366,9 +373,6 @@ class HPCQuantizeGUI:
366
  ttk.Label(
367
  self.custom_frame, textvariable=self.custom_hint_var, style="TeleKey.TLabel"
368
  ).pack(anchor=tk.W, pady=(4, 0))
369
- ttk.Label(
370
- self.custom_frame, textvariable=self.custom_size_var
371
- ).pack(anchor=tk.W, pady=(2, 0))
372
 
373
  opt_row = ttk.Frame(opt_frame)
374
  opt_row.pack(fill=tk.X, pady=(0, 4))
@@ -473,7 +477,7 @@ class HPCQuantizeGUI:
473
  filter_entry = ttk.Entry(search_row, textvariable=self.filter_var)
474
  filter_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
475
  filter_entry.bind("<KeyRelease>", lambda _e: self._populate_tensor_tree())
476
- for label, val in (("All", "ALL"), ("Q1_0", "Q1_0"), ("Q2_K", "Q2_K"), ("Q4_0", "Q4_0"), ("Copy", "COPY")):
477
  ttk.Radiobutton(
478
  search_row,
479
  text=label,
@@ -496,6 +500,7 @@ class HPCQuantizeGUI:
496
  self.tree.heading("state", text="Live Status / RMSE")
497
  self.tree.tag_configure("Q1_0", foreground="#fbbf24")
498
  self.tree.tag_configure("Q2_K", foreground="#93c5fd")
 
499
  self.tree.tag_configure("Q4_0", foreground="#34d399")
500
  self.tree.tag_configure("Copy", foreground="#9ca3af")
501
 
@@ -629,6 +634,8 @@ class HPCQuantizeGUI:
629
  return "-Q1_0-Q4_0.gguf"
630
  if fmt == "custom":
631
  return "-Custom.gguf"
 
 
632
  if fmt == "q4_0":
633
  return "-Q4_0.gguf"
634
  return "-Q2K.gguf"
@@ -640,7 +647,7 @@ class HPCQuantizeGUI:
640
  not cur_out
641
  or any(
642
  cur_out.endswith(sfx)
643
- for sfx in ("-Q2K.gguf", "-Q1_0.gguf", "-Q1_0-Q4_0.gguf", "-Custom.gguf", "-Q4_0.gguf")
644
  )
645
  ):
646
  p = Path(gguf_p)
@@ -689,6 +696,8 @@ class HPCQuantizeGUI:
689
  options.append("Q1_0")
690
  if any(is_q2k_eligible(t.name, t.dims) for t in tensors):
691
  options.append("Q2_K")
 
 
692
  if any(
693
  is_q4_0_eligible(t.name, t.dims, include_embd=True, allow_q2k_tensors=True)
694
  for t in tensors
@@ -719,20 +728,10 @@ class HPCQuantizeGUI:
719
  ).grid(row=r, column=c * 2 + 1, sticky=tk.W, padx=(0, 12), pady=1)
720
  rows += 1
721
 
722
- hint = (
723
  "Quantizable tensor types only; norms/1D tensors and other non-eligible "
724
  "weights are copied unchanged."
725
  )
726
- unsupported = sorted(
727
- {ti.type_name for ti in self._reader.tensors if ti.type not in SUPPORTED_READ_TYPES}
728
- )
729
- if unsupported:
730
- hint += (
731
- " Copy-only source formats (cannot down-quantize): "
732
- + ", ".join(unsupported)
733
- + "."
734
- )
735
- self.custom_hint_var.set(hint)
736
  self._update_cli_preview()
737
 
738
  def _on_custom_type_changed(self) -> None:
@@ -795,7 +794,7 @@ class HPCQuantizeGUI:
795
  sse_budget=float(self.sse_budget_var.get()),
796
  quant_format=self.quant_format_var.get(),
797
  custom_quant_map=self._custom_map_for_plan() or {},
798
- enable_q4_fallback=bool(self.q4_fallback_var.get()) and self.quant_format_var.get() != "q2_k",
799
  quantize_embd_q4=bool(self.embd_q4_var.get()),
800
  promote_attn_q4=bool(self.promote_attn_q4_var.get()),
801
  device=self.device_var.get(),
@@ -848,31 +847,6 @@ class HPCQuantizeGUI:
848
  self.cli_preview_var.set(self.build_cli_command())
849
  except Exception:
850
  pass
851
- self._update_projected_size()
852
-
853
- def _update_projected_size(self) -> None:
854
- if self.quant_format_var.get() != "custom":
855
- self.custom_size_var.set("Projected GGUF size: switch to Custom mode")
856
- return
857
- if self._reader is None:
858
- self.custom_size_var.set("Projected GGUF size: load a source GGUF")
859
- return
860
- try:
861
- size = estimate_gguf_size(
862
- self._reader,
863
- enable_q4_fallback=bool(self.q4_fallback_var.get())
864
- and self.quant_format_var.get() != "q2_k",
865
- quantize_embd_q4=bool(self.embd_q4_var.get()),
866
- promote_attn_q4=bool(self.promote_attn_q4_var.get()),
867
- quant_format=self.quant_format_var.get(),
868
- custom_quant_map=self._custom_map_for_plan(),
869
- )
870
- except Exception as exc:
871
- self.custom_size_var.set(f"Projected GGUF size: unavailable ({exc})")
872
- return
873
- self.custom_size_var.set(
874
- f"Projected GGUF size: {size / 1024**3:.2f} GiB ({size / 1e9:.2f} GB)"
875
- )
876
 
877
  def _copy_cli(self) -> None:
878
  cmd = self.cli_preview_var.get()
@@ -910,24 +884,24 @@ class HPCQuantizeGUI:
910
  return
911
  filt = self.filter_var.get().strip().lower()
912
  plan_filt = self.plan_filter_var.get()
913
- n_q2, n_q4, n_copy = 0, 0, 0
914
  n_q1 = 0
 
915
  for ti in self._reader.tensors:
916
- requested_tgt = target_quant_type(
917
  ti.name,
918
  ti.dims,
919
- enable_q4_fallback=bool(self.q4_fallback_var.get()) and self.quant_format_var.get() != "q2_k",
920
  quantize_embd_q4=bool(self.embd_q4_var.get()),
921
  promote_attn_q4=bool(self.promote_attn_q4_var.get()),
922
  quant_format=self.quant_format_var.get(),
923
  source_type=ti.type,
924
  custom_quant_map=self._custom_map_for_plan(),
925
  )
926
- tgt = requested_tgt
927
- if tgt is not None and ti.type not in SUPPORTED_READ_TYPES:
928
- tgt = None
929
  if tgt == "Q2_K":
930
  n_q2 += 1
 
 
931
  elif tgt == "Q4_0":
932
  n_q4 += 1
933
  elif tgt == "Q1_0":
@@ -935,6 +909,17 @@ class HPCQuantizeGUI:
935
  else:
936
  n_copy += 1
937
 
 
 
 
 
 
 
 
 
 
 
 
938
  tgt_label = tgt if tgt else "Copy"
939
  if plan_filt != "ALL" and tgt_label.upper() != plan_filt:
940
  continue
@@ -949,14 +934,11 @@ class HPCQuantizeGUI:
949
  self._imatrix is not None
950
  and lookup_imatrix(self._imatrix, ti.name) is not None
951
  )
952
- if tgt:
953
- state_str = f"Pending ({tgt_label})"
954
- elif requested_tgt:
955
- state_str = f"Copy {ti.type_name} (cannot dequantize for {requested_tgt})"
956
- elif ti.type_name in ("Q1_0", "Q2_K", "Q4_0"):
957
- state_str = f"Keep {ti.type_name} (<= target)"
958
- else:
959
- state_str = "Passthrough"
960
  self.tree.insert(
961
  "",
962
  tk.END,
@@ -972,8 +954,15 @@ class HPCQuantizeGUI:
972
  state_str,
973
  ),
974
  )
 
 
 
 
 
 
975
  self.status_var.set(
976
- f"Plan ({self.quant_format_var.get().upper()}): {n_q1} Q1_0 | {n_q2} Q2_K | {n_q4} Q4_0 | {n_copy} Copy (Total: {len(self._reader.tensors)} tensors)"
 
977
  )
978
 
979
  def _select_all_eligible(self) -> None:
@@ -985,7 +974,7 @@ class HPCQuantizeGUI:
985
  if target_quant_type(
986
  ti.name,
987
  ti.dims,
988
- enable_q4_fallback=bool(self.q4_fallback_var.get()) and self.quant_format_var.get() != "q2_k",
989
  quantize_embd_q4=bool(self.embd_q4_var.get()),
990
  promote_attn_q4=bool(self.promote_attn_q4_var.get()),
991
  quant_format=self.quant_format_var.get(),
@@ -993,7 +982,6 @@ class HPCQuantizeGUI:
993
  custom_quant_map=self._custom_map_for_plan(),
994
  )
995
  is not None
996
- and ti.type in SUPPORTED_READ_TYPES
997
  and self.tree.exists(ti.name)
998
  ]
999
  self.tree.selection_set(eligible_ids)
@@ -1077,10 +1065,6 @@ class HPCQuantizeGUI:
1077
  reader = GGUFReader(gguf_path)
1078
  tname = next(iter(selected))
1079
  ti = reader.info(tname)
1080
- if ti.type not in SUPPORTED_READ_TYPES:
1081
- raise ValueError(
1082
- f"{tname}: cannot dequantize source type {ti.type_name} for .npz export"
1083
- )
1084
  x, row = reader.read_tensor(tname)
1085
  imp = None
1086
  if imat is not None:
@@ -1109,6 +1093,18 @@ class HPCQuantizeGUI:
1109
  ("done", f"Saved Q1_0 {out_path} (RMSE={rmse_q1:.6e}, {time.time() - t0:.1f}s)")
1110
  )
1111
  return
 
 
 
 
 
 
 
 
 
 
 
 
1112
  if tgt == "Q4_0":
1113
  raw_q4, nb_q4, rmse_q4 = quantize_tensor_q4_0(x, importance=imp, cfg=cfg)
1114
  np.savez_compressed(
@@ -1166,7 +1162,8 @@ class HPCQuantizeGUI:
1166
  self._log_queue.put(
1167
  (
1168
  "done",
1169
- f"Wrote {out_path}: {int(stats.get('q1_0', 0))} Q1_0 + {int(stats.get('q2_k', 0))} Q2_K + {int(stats.get('q4_0', 0))} Q4_0 "
 
1170
  f"({int(stats['quantized'])}/{int(stats['tensors'])} tensors), "
1171
  f"overall RMSE={stats['rmse']:.6e} ({dt_sec:.1f}s)",
1172
  )
@@ -1310,7 +1307,7 @@ class HPCQuantizeGUI:
1310
  done, total, name, action, rmse, has_imat = payload # type: ignore[misc]
1311
  self.model_progress_var.set(100.0 * done / max(total, 1))
1312
  self.tensor_progress_var.set(100.0)
1313
- if action in ("Q1_0", "Q2_K", "Q4_0") and rmse is not None:
1314
  self._update_tree_row_state(name, f"{action} (RMSE={rmse:.4e})")
1315
  self._log(
1316
  f"[{done}/{total}] FINISHED {name:42s} -> {action} RMSE={rmse:.6e} (iMatrix={'yes' if has_imat else 'no'})"
 
49
  from hpc_quantize_v2 import (
50
  GGUFReader,
51
  HPCConfig,
52
+ Q1_0_BLOCK_BYTES,
53
  Q2KQuantizer,
54
+ Q3_K_BLOCK_BYTES,
55
+ QK1_0,
56
+ QK3_K,
57
+ QK4_0,
58
+ QK_K,
59
  cuda_device_name,
60
  cuda_is_available,
61
  dequantize_q1_0_bytes,
62
+ dequantize_q3_k_bytes,
63
  dequantize_q4_0_bytes,
64
  expand_importance,
65
  factor_only_solve,
66
  lookup_imatrix,
67
  quantize_tensor_q1_0,
68
+ quantize_tensor_q3_k,
69
  quantize_tensor_q4_0,
70
  read_imatrix,
71
  )
72
  from hpc_quantize_v2.gguf import (
 
 
73
  is_q1_0_eligible,
74
  is_q2k_eligible,
75
+ is_q3_k_eligible,
76
  is_q4_0_eligible,
77
  target_quant_type,
78
  tensor_type_key,
 
123
  class HPCQuantizeGUI:
124
  def __init__(self, root: tk.Tk) -> None:
125
  self.root = root
126
+ self.root.title("HPC-Quantize V2 — Factored Q1_0 / Q2_K / Q3_K / Q4_0 & Geometry-Preserving Analog Engine")
127
  self.root.geometry("1260x900")
128
  self.root.minsize(1040, 740)
129
 
 
183
  self.sse_budget_var = tk.DoubleVar(value=0.0005)
184
 
185
  self.cli_preview_var = tk.StringVar()
 
186
  self.status_var = tk.StringVar(value="Ready.")
187
  self.model_progress_var = tk.DoubleVar(value=0.0)
188
  self.tensor_progress_var = tk.DoubleVar(value=0.0)
 
320
  mid.add(right_pane, weight=3)
321
 
322
  # Left: Engine & Factorization Options
323
+ opt_frame = ttk.LabelFrame(left_pane, text="2. Factored Q1_0 / Q2_K / Q3_K / Q4_0 & Analog Controls", padding=8)
324
  opt_frame.pack(fill=tk.BOTH, expand=True, padx=(0, 6))
325
 
326
  mode_row = ttk.Frame(opt_frame)
 
341
  ("Mixed Q1_0 + Q4_0", "mixed_q1"),
342
  ("Pure Q1_0 (1.125 bpw)", "q1_0"),
343
  ("Pure Q2_K (2.625 bpw)", "q2_k"),
344
+ ("Pure Q3_K (3.438 bpw)", "q3_k"),
345
  ("Pure Q4_0 (4.500 bpw)", "q4_0"),
346
  ):
347
  ttk.Radiobutton(
 
373
  ttk.Label(
374
  self.custom_frame, textvariable=self.custom_hint_var, style="TeleKey.TLabel"
375
  ).pack(anchor=tk.W, pady=(4, 0))
 
 
 
376
 
377
  opt_row = ttk.Frame(opt_frame)
378
  opt_row.pack(fill=tk.X, pady=(0, 4))
 
477
  filter_entry = ttk.Entry(search_row, textvariable=self.filter_var)
478
  filter_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
479
  filter_entry.bind("<KeyRelease>", lambda _e: self._populate_tensor_tree())
480
+ for label, val in (("All", "ALL"), ("Q1_0", "Q1_0"), ("Q2_K", "Q2_K"), ("Q3_K", "Q3_K"), ("Q4_0", "Q4_0"), ("Copy", "COPY")):
481
  ttk.Radiobutton(
482
  search_row,
483
  text=label,
 
500
  self.tree.heading("state", text="Live Status / RMSE")
501
  self.tree.tag_configure("Q1_0", foreground="#fbbf24")
502
  self.tree.tag_configure("Q2_K", foreground="#93c5fd")
503
+ self.tree.tag_configure("Q3_K", foreground="#c4b5fd")
504
  self.tree.tag_configure("Q4_0", foreground="#34d399")
505
  self.tree.tag_configure("Copy", foreground="#9ca3af")
506
 
 
634
  return "-Q1_0-Q4_0.gguf"
635
  if fmt == "custom":
636
  return "-Custom.gguf"
637
+ if fmt == "q3_k":
638
+ return "-Q3_K.gguf"
639
  if fmt == "q4_0":
640
  return "-Q4_0.gguf"
641
  return "-Q2K.gguf"
 
647
  not cur_out
648
  or any(
649
  cur_out.endswith(sfx)
650
+ for sfx in ("-Q2K.gguf", "-Q3_K.gguf", "-Q1_0.gguf", "-Q1_0-Q4_0.gguf", "-Custom.gguf", "-Q4_0.gguf")
651
  )
652
  ):
653
  p = Path(gguf_p)
 
696
  options.append("Q1_0")
697
  if any(is_q2k_eligible(t.name, t.dims) for t in tensors):
698
  options.append("Q2_K")
699
+ if any(is_q3_k_eligible(t.name, t.dims) for t in tensors):
700
+ options.append("Q3_K")
701
  if any(
702
  is_q4_0_eligible(t.name, t.dims, include_embd=True, allow_q2k_tensors=True)
703
  for t in tensors
 
728
  ).grid(row=r, column=c * 2 + 1, sticky=tk.W, padx=(0, 12), pady=1)
729
  rows += 1
730
 
731
+ self.custom_hint_var.set(
732
  "Quantizable tensor types only; norms/1D tensors and other non-eligible "
733
  "weights are copied unchanged."
734
  )
 
 
 
 
 
 
 
 
 
 
735
  self._update_cli_preview()
736
 
737
  def _on_custom_type_changed(self) -> None:
 
794
  sse_budget=float(self.sse_budget_var.get()),
795
  quant_format=self.quant_format_var.get(),
796
  custom_quant_map=self._custom_map_for_plan() or {},
797
+ enable_q4_fallback=bool(self.q4_fallback_var.get()) and self.quant_format_var.get() not in ("q2_k", "q3_k"),
798
  quantize_embd_q4=bool(self.embd_q4_var.get()),
799
  promote_attn_q4=bool(self.promote_attn_q4_var.get()),
800
  device=self.device_var.get(),
 
847
  self.cli_preview_var.set(self.build_cli_command())
848
  except Exception:
849
  pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
850
 
851
  def _copy_cli(self) -> None:
852
  cmd = self.cli_preview_var.get()
 
884
  return
885
  filt = self.filter_var.get().strip().lower()
886
  plan_filt = self.plan_filter_var.get()
887
+ n_q2, n_q3, n_q4, n_copy = 0, 0, 0, 0
888
  n_q1 = 0
889
+ planned_bytes = 0
890
  for ti in self._reader.tensors:
891
+ tgt = target_quant_type(
892
  ti.name,
893
  ti.dims,
894
+ enable_q4_fallback=bool(self.q4_fallback_var.get()) and self.quant_format_var.get() not in ("q2_k", "q3_k"),
895
  quantize_embd_q4=bool(self.embd_q4_var.get()),
896
  promote_attn_q4=bool(self.promote_attn_q4_var.get()),
897
  quant_format=self.quant_format_var.get(),
898
  source_type=ti.type,
899
  custom_quant_map=self._custom_map_for_plan(),
900
  )
 
 
 
901
  if tgt == "Q2_K":
902
  n_q2 += 1
903
+ elif tgt == "Q3_K":
904
+ n_q3 += 1
905
  elif tgt == "Q4_0":
906
  n_q4 += 1
907
  elif tgt == "Q1_0":
 
909
  else:
910
  n_copy += 1
911
 
912
+ if tgt == "Q2_K":
913
+ planned_bytes += (ti.n_elements // QK_K) * 84
914
+ elif tgt == "Q3_K":
915
+ planned_bytes += (ti.n_elements // QK3_K) * Q3_K_BLOCK_BYTES
916
+ elif tgt == "Q4_0":
917
+ planned_bytes += (ti.n_elements // QK4_0) * 18
918
+ elif tgt == "Q1_0":
919
+ planned_bytes += (ti.n_elements // QK1_0) * Q1_0_BLOCK_BYTES
920
+ else:
921
+ planned_bytes += ti.n_bytes
922
+
923
  tgt_label = tgt if tgt else "Copy"
924
  if plan_filt != "ALL" and tgt_label.upper() != plan_filt:
925
  continue
 
934
  self._imatrix is not None
935
  and lookup_imatrix(self._imatrix, ti.name) is not None
936
  )
937
+ state_str = (
938
+ f"Pending ({tgt_label})"
939
+ if tgt
940
+ else (f"Keep {ti.type_name} (<= target)" if ti.type_name in ("Q1_0", "Q2_K", "Q3_K", "Q4_0") else "Passthrough")
941
+ )
 
 
 
942
  self.tree.insert(
943
  "",
944
  tk.END,
 
954
  state_str,
955
  ),
956
  )
957
+ if planned_bytes >= 1024 ** 3:
958
+ planned_text = f"{planned_bytes / (1024 ** 3):.2f} GiB"
959
+ elif planned_bytes >= 1024 ** 2:
960
+ planned_text = f"{planned_bytes / (1024 ** 2):.1f} MiB"
961
+ else:
962
+ planned_text = f"{planned_bytes / 1024:.1f} KiB"
963
  self.status_var.set(
964
+ f"Plan ({self.quant_format_var.get().upper()}): {n_q1} Q1_0 | {n_q2} Q2_K | {n_q3} Q3_K | {n_q4} Q4_0 | {n_copy} Copy "
965
+ f"(Total: {len(self._reader.tensors)} tensors, est. {planned_text})"
966
  )
967
 
968
  def _select_all_eligible(self) -> None:
 
974
  if target_quant_type(
975
  ti.name,
976
  ti.dims,
977
+ enable_q4_fallback=bool(self.q4_fallback_var.get()) and self.quant_format_var.get() not in ("q2_k", "q3_k"),
978
  quantize_embd_q4=bool(self.embd_q4_var.get()),
979
  promote_attn_q4=bool(self.promote_attn_q4_var.get()),
980
  quant_format=self.quant_format_var.get(),
 
982
  custom_quant_map=self._custom_map_for_plan(),
983
  )
984
  is not None
 
985
  and self.tree.exists(ti.name)
986
  ]
987
  self.tree.selection_set(eligible_ids)
 
1065
  reader = GGUFReader(gguf_path)
1066
  tname = next(iter(selected))
1067
  ti = reader.info(tname)
 
 
 
 
1068
  x, row = reader.read_tensor(tname)
1069
  imp = None
1070
  if imat is not None:
 
1093
  ("done", f"Saved Q1_0 {out_path} (RMSE={rmse_q1:.6e}, {time.time() - t0:.1f}s)")
1094
  )
1095
  return
1096
+ if tgt == "Q3_K":
1097
+ raw_q3, nb_q3, rmse_q3 = quantize_tensor_q3_k(x, importance=imp, cfg=cfg)
1098
+ np.savez_compressed(
1099
+ out_path,
1100
+ q3_k_bytes=np.frombuffer(raw_q3, dtype=np.uint8),
1101
+ dequantized=dequantize_q3_k_bytes(raw_q3, nb_q3),
1102
+ rmse=np.float32(rmse_q3),
1103
+ )
1104
+ self._log_queue.put(
1105
+ ("done", f"Saved Q3_K {out_path} (RMSE={rmse_q3:.6e}, {time.time() - t0:.1f}s)")
1106
+ )
1107
+ return
1108
  if tgt == "Q4_0":
1109
  raw_q4, nb_q4, rmse_q4 = quantize_tensor_q4_0(x, importance=imp, cfg=cfg)
1110
  np.savez_compressed(
 
1162
  self._log_queue.put(
1163
  (
1164
  "done",
1165
+ f"Wrote {out_path}: {int(stats.get('q1_0', 0))} Q1_0 + {int(stats.get('q2_k', 0))} Q2_K + "
1166
+ f"{int(stats.get('q3_k', 0))} Q3_K + {int(stats.get('q4_0', 0))} Q4_0 "
1167
  f"({int(stats['quantized'])}/{int(stats['tensors'])} tensors), "
1168
  f"overall RMSE={stats['rmse']:.6e} ({dt_sec:.1f}s)",
1169
  )
 
1307
  done, total, name, action, rmse, has_imat = payload # type: ignore[misc]
1308
  self.model_progress_var.set(100.0 * done / max(total, 1))
1309
  self.tensor_progress_var.set(100.0)
1310
+ if action in ("Q1_0", "Q2_K", "Q3_K", "Q4_0") and rmse is not None:
1311
  self._update_tree_row_state(name, f"{action} (RMSE={rmse:.4e})")
1312
  self._log(
1313
  f"[{done}/{total}] FINISHED {name:42s} -> {action} RMSE={rmse:.6e} (iMatrix={'yes' if has_imat else 'no'})"
q3_k.py ADDED
@@ -0,0 +1,715 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Full HPC V2 Q3_K quantizer.
2
+
3
+ Implements the HPC-Quantize V2 decision stack for llama.cpp/GGML ``Q3_K``
4
+ (256 weights per 110-byte block = 3.4375 bpw):
5
+
6
+ 1. **Geometry-Preserving Analog + WLS Seeds**:
7
+ Finds an optimal signed scale from the raw weights and an iso-moment
8
+ companded analog for every 16-weight sub-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.
13
+ 3. **6-State Sequential Sieve & 6-State Viterbi DP**:
14
+ Runs the 6-state sequential Sieve with parity back-action and a 6-state
15
+ Viterbi dynamic program across the sub-block chain.
16
+ 4. **Asymmetric Sign-Flip fp16-ULP Polish & Closed-Form Vesica/DC Shaping**:
17
+ Polishes each sub-block scale over ``+/-8`` fp16 ULPs, then jointly fits the
18
+ GGML super-scale ``d`` and signed 6-bit sub-block scales ``sc``. The final
19
+ 3-bit codes ``[-4, +3]`` are emitted in the exact ``block_q3_K`` layout.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from math import ceil
25
+ import numpy as np
26
+
27
+ try:
28
+ import torch
29
+ except ImportError: # pragma: no cover
30
+ torch = None # type: ignore[assignment]
31
+
32
+ from .config import HPCConfig
33
+ from .cuda_backend import cuda_is_available
34
+ from .factored import MULTS_D
35
+ from .fp16 import from_fp16_bits, nearest_int, to_fp16_bits
36
+ from .sieve import sieve_measure_chain, subblock_chain_edges
37
+ from .viterbi import robust_temperature
38
+
39
+ QK3_K = 256
40
+ Q3_K_BLOCK_BYTES = 110
41
+ Q3_K_SUBBLOCK = 16
42
+ Q3_K_N_SUBBLOCKS = QK3_K // Q3_K_SUBBLOCK
43
+ Q3_N_CAND = 24
44
+ Q3_N_STATES = 6
45
+
46
+
47
+ def _nearest_int_t(value):
48
+ """GGML round-to-nearest-even for torch tensors."""
49
+ shifted = value + 12582912.0
50
+ return (shifted.view(torch.int32) & 0x007FFFFF) - 0x00400000
51
+
52
+
53
+ def _unpack_q3_k_scales(scales: np.ndarray) -> np.ndarray:
54
+ """Decode the 12-byte GGML Q3_K scale field into signed values [-32, 31]."""
55
+ scales = np.asarray(scales, dtype=np.uint8)
56
+ B = scales.shape[0]
57
+ vals = np.empty((B, Q3_K_N_SUBBLOCKS), dtype=np.uint8)
58
+ for j in range(8):
59
+ vals[:, j] = scales[:, j] & np.uint8(0x0F)
60
+ vals[:, j + 8] = scales[:, j] >> np.uint8(4)
61
+ for j in range(Q3_K_N_SUBBLOCKS):
62
+ hi = (scales[:, 8 + (j % 4)] >> np.uint8(2 * (j // 4))) & np.uint8(0x03)
63
+ vals[:, j] |= hi << np.uint8(4)
64
+ return vals.astype(np.int16) - 32
65
+
66
+
67
+ def _pack_q3_k_scales(scales: np.ndarray) -> np.ndarray:
68
+ """Encode signed 6-bit scales [-32, 31] into the 12-byte GGML field."""
69
+ sc = np.asarray(scales, dtype=np.int16).reshape(-1, Q3_K_N_SUBBLOCKS)
70
+ B = sc.shape[0]
71
+ vals = np.clip(sc + 32, 0, 63).astype(np.uint8)
72
+ out = np.zeros((B, 12), dtype=np.uint8)
73
+ for j in range(8):
74
+ out[:, j] = vals[:, j] & np.uint8(0x0F)
75
+ out[:, j] |= (vals[:, j + 8] & np.uint8(0x0F)) << np.uint8(4)
76
+ for j in range(Q3_K_N_SUBBLOCKS):
77
+ hi = (vals[:, j] >> np.uint8(4)) & np.uint8(0x03)
78
+ out[:, 8 + (j % 4)] |= hi << np.uint8(2 * (j // 4))
79
+ return out
80
+
81
+
82
+ def _pack_q3_k_codes(codes: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
83
+ """Pack signed 3-bit codes [-4, 3] into GGML hmask[32] + qs[64]."""
84
+ c = np.asarray(codes, dtype=np.int16).reshape(-1, QK3_K)
85
+ B = c.shape[0]
86
+ low = (c & 3).astype(np.uint8)
87
+ hmask = np.zeros((B, QK3_K // 8), dtype=np.uint8)
88
+ high = c >= 0
89
+ for bit in range(8):
90
+ group = high[:, bit * 32 : (bit + 1) * 32]
91
+ hmask |= group.astype(np.uint8) << np.uint8(bit)
92
+ qs = np.empty((B, QK3_K // 4), dtype=np.uint8)
93
+ qs[:, :32] = (
94
+ low[:, 0:32]
95
+ | (low[:, 32:64] << np.uint8(2))
96
+ | (low[:, 64:96] << np.uint8(4))
97
+ | (low[:, 96:128] << np.uint8(6))
98
+ )
99
+ qs[:, 32:] = (
100
+ low[:, 128:160]
101
+ | (low[:, 160:192] << np.uint8(2))
102
+ | (low[:, 192:224] << np.uint8(4))
103
+ | (low[:, 224:256] << np.uint8(6))
104
+ )
105
+ return hmask, qs
106
+
107
+
108
+ def dequantize_q3_k_bytes(raw: bytes | np.ndarray, n_blocks: int) -> np.ndarray:
109
+ """Decode GGML Q3_K blocks into float32 weights."""
110
+ blocks = np.frombuffer(raw, dtype=np.uint8).reshape(n_blocks, Q3_K_BLOCK_BYTES)
111
+ hmask = blocks[:, : QK3_K // 8]
112
+ qs = blocks[:, QK3_K // 8 : QK3_K // 8 + QK3_K // 4]
113
+ sc = _unpack_q3_k_scales(blocks[:, QK3_K // 8 + QK3_K // 4 : Q3_K_BLOCK_BYTES - 2])
114
+ d = blocks[:, Q3_K_BLOCK_BYTES - 2 :].copy().view("<f2").reshape(n_blocks, 1)
115
+
116
+ out = np.empty((n_blocks, QK3_K), dtype=np.float32)
117
+ for sb in range(Q3_K_N_SUBBLOCKS):
118
+ group = sb // 2
119
+ l0 = (sb % 2) * 16
120
+ l = np.arange(l0, l0 + 16)
121
+ shift = np.uint8(2 * (group % 4))
122
+ qoff = 0 if group < 4 else 32
123
+ low = (qs[:, qoff + l] >> shift) & np.uint8(0x03)
124
+ high = (hmask[:, l] >> np.uint8(group)) & np.uint8(0x01)
125
+ code = low.astype(np.int16) - np.where(high != 0, 0, 4).astype(np.int16)
126
+ scale = d * sc[:, sb : sb + 1].astype(np.float32)
127
+ out[:, sb * 16 : (sb + 1) * 16] = scale * code.astype(np.float32)
128
+ return out.reshape(-1)
129
+
130
+
131
+ def _q3_sieve_and_viterbi(cand_errors: np.ndarray, cfg: HPCConfig) -> np.ndarray:
132
+ """6-state sequential Sieve + 6-state Viterbi DP over a Q3 candidate lattice."""
133
+ B = cand_errors.shape[0]
134
+ if cfg.optimizer != "hpc" or B < 2:
135
+ return np.argmin(cand_errors, axis=1).astype(np.int64)
136
+
137
+ max_gb = min(int(cfg.graph_max_blocks), 512)
138
+ stride = max(1, ceil(B / max_gb))
139
+ gb = ceil(B / stride)
140
+ temp = max(float(robust_temperature(cand_errors, cfg)), 1.0e-12)
141
+
142
+ pad = gb * stride - B
143
+ ce = cand_errors.astype(np.float64)
144
+ if pad > 0:
145
+ ce = np.concatenate([ce, np.full((pad, Q3_N_CAND), np.inf, dtype=np.float64)], axis=0)
146
+ ce_grouped = ce.reshape(gb, stride, Q3_N_STATES, 4)
147
+
148
+ group_min = np.min(ce_grouped, axis=(1, 3))
149
+ finite = np.isfinite(ce_grouped)
150
+ counts = np.sum(finite, axis=(1, 3))
151
+ valid = (counts > 0) & np.isfinite(group_min)
152
+ gm_b = np.where(np.isfinite(group_min), group_min, 0.0)[:, None, :, None]
153
+ shifted = np.where(finite, (ce_grouped - gm_b) / (2.0 * temp), np.inf)
154
+ sums = np.sum(np.exp(-shifted), axis=(1, 3))
155
+ mean_exp = np.maximum(sums / np.maximum(counts, 1), 1.0e-300)
156
+ bin_err = np.where(valid, group_min - 2.0 * temp * np.log(mean_exp), np.inf)
157
+
158
+ agg = np.mean(np.where(finite, ce_grouped, 0.0), axis=1).reshape(gb, Q3_N_CAND)
159
+ mn = np.min(agg, axis=1, keepdims=True)
160
+ coeff = np.exp(-np.clip((agg - mn) / (2.0 * temp), 0.0, 80.0)).reshape(gb, Q3_N_STATES, 4)
161
+ amps = np.sum(coeff, axis=2)
162
+ norms = np.linalg.norm(amps, axis=1, keepdims=True)
163
+ amps = np.where(norms > 1.0e-30, amps / np.maximum(norms, 1.0e-30), 1.0 / np.sqrt(6.0))
164
+
165
+ marg, _ = sieve_measure_chain(
166
+ amps,
167
+ subblock_chain_edges(gb),
168
+ same_penalty=cfg.same_penalty,
169
+ log_slack=cfg.log_slack,
170
+ deterministic=True,
171
+ )
172
+ m_tot = np.sum(marg, axis=1, keepdims=True)
173
+ pm = np.where(m_tot > 1.0e-30, marg / np.maximum(m_tot, 1.0e-30), 1.0 / 6.0)
174
+ log_prior = np.log(pm + 1.0e-30)
175
+
176
+ fin_err = bin_err[np.isfinite(bin_err)]
177
+ scale_err = max(float(fin_err.mean()) if fin_err.size else 1.0e-10, 1.0e-20)
178
+ local = np.where(np.isfinite(bin_err), bin_err - cfg.viterbi_beta * scale_err * log_prior, np.inf)
179
+
180
+ states = np.arange(Q3_N_STATES)
181
+ trans = cfg.viterbi_alpha * scale_err * np.abs(states[None, :] - states[:, None])
182
+ dp = np.full((gb, Q3_N_STATES), np.inf, dtype=np.float64)
183
+ back = np.zeros((gb, Q3_N_STATES), dtype=np.int64)
184
+ dp[0] = local[0]
185
+ for gi in range(1, gb):
186
+ totals = dp[gi - 1][:, None] + trans
187
+ best_sp = np.argmin(totals, axis=0)
188
+ best_val = totals[best_sp, states]
189
+ dp[gi] = np.where(np.isfinite(best_val), best_val + local[gi], np.inf)
190
+ back[gi] = best_sp
191
+
192
+ path = np.zeros(gb, dtype=np.int64)
193
+ if np.any(np.isfinite(dp[-1])):
194
+ path[-1] = int(np.argmin(dp[-1]))
195
+ for gi in range(gb - 2, -1, -1):
196
+ path[gi] = back[gi + 1, path[gi + 1]]
197
+
198
+ ce_bins = cand_errors.reshape(B, Q3_N_STATES, 4)
199
+ bin_local_arg = np.argmin(ce_bins, axis=2)
200
+ blk_gi = np.arange(B) // stride
201
+ chosen_bin = path[blk_gi]
202
+ chosen_cand = chosen_bin * 4 + bin_local_arg[np.arange(B), chosen_bin]
203
+
204
+ global_best = np.argmin(cand_errors, axis=1).astype(np.int64)
205
+ cur_e = cand_errors[np.arange(B), chosen_cand]
206
+ g_e = cand_errors[np.arange(B), global_best]
207
+ return np.where(g_e < cur_e * cfg.greedy_override_ratio, global_best, chosen_cand)
208
+
209
+
210
+ def _subblock_scales_hpc(
211
+ X: np.ndarray, W: np.ndarray, cfg: HPCConfig
212
+ ) -> np.ndarray:
213
+ """Run the HPC 3-bit pipeline on (M, 16) sub-blocks and return signed scales."""
214
+ M = X.shape[0]
215
+ X_f32 = X.astype(np.float32)
216
+ W_f32 = W.astype(np.float32)
217
+ lam_dc = (float(cfg.dc_lambda) / Q3_K_SUBBLOCK) if cfg.use_spectral else 0.0
218
+ lam_vw = (float(cfg.vw_lambda) / Q3_K_SUBBLOCK) if cfg.use_spectral else 0.0
219
+ half = Q3_K_SUBBLOCK // 2
220
+
221
+ amax = np.max(np.abs(X_f32), axis=1)
222
+ d_range = amax / 3.5
223
+ wsum = np.maximum(np.sum(W_f32, axis=1, keepdims=True), 1.0e-30)
224
+ mu = np.sum(W_f32 * X_f32, axis=1, keepdims=True) / wsum
225
+ var = np.sum(W_f32 * (X_f32 - mu) ** 2, axis=1, keepdims=True) / wsum
226
+ sig = np.sqrt(np.maximum(var, 1.0e-30))
227
+ x_comp = mu + sig * 1.85 * np.tanh((X_f32 - mu) / (1.85 * sig))
228
+ d_analog = np.max(np.abs(x_comp), axis=1).astype(np.float32) / 3.5
229
+
230
+ wls_d = d_range.copy()
231
+ best_seed_sse = np.full(M, np.inf, dtype=np.float64)
232
+ for d_start in (d_range, -d_range, d_analog, -d_analog):
233
+ d = d_start.astype(np.float64)
234
+ for _ in range(4):
235
+ act = np.abs(d) > 1.0e-15
236
+ sd = np.where(act, d, 1.0)[:, None]
237
+ q = np.where(act[:, None], np.clip(nearest_int((X_f32 / sd).astype(np.float32)) + 4, 0, 7), 4)
238
+ c = (q - 4).astype(np.float64)
239
+ num = np.sum(W_f32 * X_f32 * c, axis=1, dtype=np.float64)
240
+ den = np.sum(W_f32 * c * c, axis=1, dtype=np.float64)
241
+ valid = den > 1.0e-30
242
+ d = np.where(valid, num / np.where(valid, den, 1.0), 0.0)
243
+ df = from_fp16_bits(to_fp16_bits(d.astype(np.float32)))
244
+ act = np.abs(df) > 1.0e-15
245
+ sdf = np.where(act, df, 1.0)[:, None]
246
+ q = np.where(act[:, None], np.clip(nearest_int(X_f32 / sdf) + 4, 0, 7), 4)
247
+ e = X_f32 - df[:, None] * (q.astype(np.float32) - 4.0)
248
+ sse = np.sum(W_f32 * e * e, axis=1, dtype=np.float64)
249
+ take = sse < best_seed_sse
250
+ best_seed_sse = np.where(take, sse, best_seed_sse)
251
+ wls_d = np.where(take, df, wls_d)
252
+
253
+ cand_d16 = to_fp16_bits(wls_d[:, None] * MULTS_D[None, :])
254
+ cand_d = from_fp16_bits(cand_d16)
255
+ act_c = np.abs(cand_d) > 1.0e-15
256
+ sd_c = np.where(act_c, cand_d, 1.0)[:, :, None]
257
+ q_c = np.where(
258
+ act_c[:, :, None],
259
+ np.clip(nearest_int(X_f32[:, None, :] / sd_c) + 4, 0, 7),
260
+ 4,
261
+ ).astype(np.float32)
262
+ e_c = X_f32[:, None, :] - cand_d[:, :, None] * (q_c - 4.0)
263
+ sse_c = np.sum(W_f32[:, None, :] * e_c * e_c, axis=2)
264
+ if cfg.use_spectral and (lam_dc > 0.0 or lam_vw > 0.0):
265
+ v_c = e_c[:, :, :half] + e_c[:, :, half:]
266
+ dc_c = np.sum(e_c, axis=2)
267
+ cand_errors = (sse_c + lam_vw * np.sum(v_c * v_c, axis=2) + lam_dc * dc_c * dc_c).astype(np.float32)
268
+ else:
269
+ cand_errors = sse_c.astype(np.float32)
270
+
271
+ best_cand = _q3_sieve_and_viterbi(cand_errors, cfg)
272
+ rows = np.arange(M)
273
+ d_sel = cand_d[rows, best_cand]
274
+
275
+ rad = max(int(cfg.ulp_radius), 4)
276
+ deltas = np.arange(-rad, rad + 1, dtype=np.int32)
277
+ pos_b = np.clip(to_fp16_bits(np.abs(d_sel)).astype(np.int32)[:, None] + deltas[None, :], 0, 0x7BFF).astype(np.uint16)
278
+ neg_b = (pos_b | np.uint16(0x8000)).astype(np.uint16)
279
+ all_b = np.concatenate([pos_b, neg_b], axis=1)
280
+ all_d = from_fp16_bits(all_b)
281
+ act_u = np.abs(all_d) > 1.0e-15
282
+ sd_u = np.where(act_u, all_d, 1.0)[:, :, None]
283
+ q_u = np.where(
284
+ act_u[:, :, None],
285
+ np.clip(nearest_int(X_f32[:, None, :] / sd_u) + 4, 0, 7),
286
+ 4,
287
+ ).astype(np.uint8)
288
+ e_u = X_f32[:, None, :] - all_d[:, :, None] * (q_u.astype(np.float32) - 4.0)
289
+ sse_u = np.sum(W_f32[:, None, :] * e_u * e_u, axis=2, dtype=np.float64)
290
+ pick_u = np.argmin(sse_u, axis=1)
291
+ best_d = all_d[rows, pick_u]
292
+ best_q = q_u[rows, pick_u].astype(np.int64)
293
+
294
+ if cfg.use_spectral and (lam_vw > 0.0 or lam_dc > 0.0):
295
+ c_f = (best_q - 4).astype(np.float64)
296
+ e = X_f32.astype(np.float64) - best_d[:, None].astype(np.float64) * c_f
297
+ sse_live = np.sum(W_f32 * e * e, axis=1, dtype=np.float64)
298
+ sse_cap = sse_live * (1.0 + cfg.sse_budget)
299
+ v = e[:, :half] + e[:, half:]
300
+ dc = np.sum(e, axis=1)
301
+ d_f64 = best_d.astype(np.float64)[:, None]
302
+ denom = (W_f32 + lam_vw + lam_dc) * (d_f64 * d_f64)
303
+ act_b = np.abs(d_f64) > 1.0e-15
304
+ s_den = np.where(act_b & (denom > 1.0e-30), denom, 1.0)
305
+ v_full = np.concatenate([v, v], axis=1)
306
+ grad = d_f64 * (W_f32 * e + lam_vw * v_full + lam_dc * dc[:, None])
307
+ dq = np.where(act_b, nearest_int((grad / s_den).astype(np.float32)), 0)
308
+ q_new = np.clip(best_q + dq, 0, 7)
309
+ e_new = X_f32.astype(np.float64) - d_f64 * (q_new - 4).astype(np.float64)
310
+ sse_new = np.sum(W_f32 * e_new * e_new, axis=1, dtype=np.float64)
311
+ v_new = e_new[:, :half] + e_new[:, half:]
312
+ dc_new = np.sum(e_new, axis=1)
313
+ spec_old = lam_vw * np.sum(v * v, axis=1) + lam_dc * dc * dc
314
+ spec_new = lam_vw * np.sum(v_new * v_new, axis=1) + lam_dc * dc_new * dc_new
315
+ accept = (sse_new <= sse_cap) & ((sse_new + spec_new) < (sse_live + spec_old) - 1.0e-15)
316
+ best_q = np.where(accept[:, None], q_new, best_q)
317
+
318
+ return best_d.astype(np.float32)
319
+
320
+
321
+ def _fit_q3_k_blocks(
322
+ X: np.ndarray, W: np.ndarray, sub_scales: np.ndarray, cfg: HPCConfig
323
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
324
+ """Fit the GGML super-scale d and signed 6-bit scales for (B, 256) blocks."""
325
+ B = X.shape[0]
326
+ X = X.reshape(B, Q3_K_N_SUBBLOCKS, Q3_K_SUBBLOCK).astype(np.float64)
327
+ W = W.reshape(B, Q3_K_N_SUBBLOCKS, Q3_K_SUBBLOCK).astype(np.float64)
328
+ s = sub_scales.reshape(B, Q3_K_N_SUBBLOCKS).astype(np.float64)
329
+ rows = np.arange(B)
330
+
331
+ max_idx = np.argmax(np.abs(s), axis=1)
332
+ max_scale = s[rows, max_idx]
333
+ d0 = np.where(np.abs(max_scale) > 1.0e-30, -max_scale / 32.0, 0.0)
334
+
335
+ cand_d16 = to_fp16_bits((d0[:, None] * MULTS_D[None, :]).astype(np.float32))
336
+ cand_d = from_fp16_bits(cand_d16).astype(np.float64)
337
+ act_d = np.abs(cand_d) > 1.0e-15
338
+ safe_d = np.where(act_d, cand_d, 1.0)
339
+ sc = np.where(
340
+ act_d[:, :, None],
341
+ np.clip(nearest_int((s[:, None, :] / safe_d[:, :, None]).astype(np.float32)), -32, 31),
342
+ 0,
343
+ )
344
+ scale = cand_d[:, :, None] * sc
345
+ act_s = np.abs(scale) > 1.0e-15
346
+ safe_s = np.where(act_s, scale, 1.0)
347
+ code = np.where(
348
+ act_s[:, :, :, None],
349
+ np.clip(nearest_int((X[:, None, :, :] / safe_s[:, :, :, None]).astype(np.float32)), -4, 3),
350
+ 0,
351
+ )
352
+ e = X[:, None, :, :] - scale[:, :, :, None] * code
353
+ sse_c = np.sum(W[:, None, :, :] * e * e, axis=(2, 3))
354
+ best_cand = _q3_sieve_and_viterbi(sse_c, cfg)
355
+ best_d16 = cand_d16[rows, best_cand]
356
+
357
+ rad = max(int(cfg.ulp_radius), 4)
358
+ deltas = np.arange(-rad, rad + 1, dtype=np.int32)
359
+ pos_b = np.clip(
360
+ to_fp16_bits(np.abs(from_fp16_bits(best_d16))).astype(np.int32)[:, None] + deltas[None, :],
361
+ 0,
362
+ 0x7BFF,
363
+ ).astype(np.uint16)
364
+ neg_b = (pos_b | np.uint16(0x8000)).astype(np.uint16)
365
+ all_b = np.concatenate([pos_b, neg_b], axis=1)
366
+ all_d = from_fp16_bits(all_b).astype(np.float64)
367
+ act_u = np.abs(all_d) > 1.0e-15
368
+ safe_u = np.where(act_u, all_d, 1.0)
369
+ sc_u = np.where(
370
+ act_u[:, :, None],
371
+ np.clip(nearest_int((s[:, None, :] / safe_u[:, :, None]).astype(np.float32)), -32, 31),
372
+ 0,
373
+ )
374
+ scale_u = all_d[:, :, None] * sc_u
375
+ act_su = np.abs(scale_u) > 1.0e-15
376
+ safe_su = np.where(act_su, scale_u, 1.0)
377
+ code_u = np.where(
378
+ act_su[:, :, :, None],
379
+ np.clip(nearest_int((X[:, None, :, :] / safe_su[:, :, :, None]).astype(np.float32)), -4, 3),
380
+ 0,
381
+ )
382
+ e_u = X[:, None, :, :] - scale_u[:, :, :, None] * code_u
383
+ sse_u = np.sum(W[:, None, :, :] * e_u * e_u, axis=(2, 3))
384
+ pick_u = np.argmin(sse_u, axis=1)
385
+ best_d16 = all_b[rows, pick_u]
386
+ best_d = all_d[rows, pick_u]
387
+
388
+ act_b = np.abs(best_d) > 1.0e-15
389
+ safe_b = np.where(act_b, best_d, 1.0)
390
+ sc = np.where(
391
+ act_b[:, None],
392
+ np.clip(nearest_int((s / safe_b[:, None]).astype(np.float32)), -32, 31),
393
+ 0,
394
+ )
395
+ scale = best_d[:, None] * sc
396
+ act_s = np.abs(scale) > 1.0e-15
397
+ safe_s = np.where(act_s, scale, 1.0)
398
+ code = np.where(
399
+ act_s[:, :, None],
400
+ np.clip(nearest_int((X / safe_s[:, :, None]).astype(np.float32)), -4, 3),
401
+ 0,
402
+ )
403
+ return best_d16.astype(np.uint16), sc.astype(np.int16), code.astype(np.int16)
404
+
405
+
406
+ def _subblock_scales_hpc_cuda(
407
+ X_np: np.ndarray, W_np: np.ndarray, dev: "torch.device", cfg: HPCConfig
408
+ ) -> np.ndarray:
409
+ """Run the HPC 3-bit sub-block pipeline on CUDA and return signed scales."""
410
+ M = X_np.shape[0]
411
+ lam_dc = (float(cfg.dc_lambda) / Q3_K_SUBBLOCK) if cfg.use_spectral else 0.0
412
+ lam_vw = (float(cfg.vw_lambda) / Q3_K_SUBBLOCK) if cfg.use_spectral else 0.0
413
+ half = Q3_K_SUBBLOCK // 2
414
+
415
+ with torch.no_grad():
416
+ X = torch.from_numpy(X_np).to(dev, dtype=torch.float32)
417
+ W = torch.from_numpy(W_np).to(dev, dtype=torch.float32)
418
+
419
+ amax = torch.max(torch.abs(X), dim=1).values
420
+ d_range = amax / 3.5
421
+ wsum = torch.clamp(torch.sum(W, dim=1, keepdim=True), min=1.0e-30)
422
+ mu = torch.sum(W * X, dim=1, keepdim=True) / wsum
423
+ var = torch.sum(W * (X - mu) ** 2, dim=1, keepdim=True) / wsum
424
+ sig = torch.sqrt(torch.clamp(var, min=1.0e-30))
425
+ x_comp = mu + sig * 1.85 * torch.tanh((X - mu) / (1.85 * sig))
426
+ d_analog = torch.max(torch.abs(x_comp), dim=1).values / 3.5
427
+
428
+ wls_d = d_range.clone()
429
+ best_seed_sse = torch.full((M,), float("inf"), dtype=torch.float32, device=dev)
430
+ for d_start in (d_range, -d_range, d_analog, -d_analog):
431
+ d = d_start.clone()
432
+ for _ in range(4):
433
+ act = torch.abs(d) > 1.0e-15
434
+ sd = torch.where(act, d, torch.ones_like(d))[:, None]
435
+ sh = (X / sd) + 12582912.0
436
+ qi = ((sh.view(torch.int32) & 0x007FFFFF) - 0x00400000 + 4).clamp(0, 7)
437
+ q = torch.where(act[:, None], qi, torch.full_like(qi, 4))
438
+ c = (q - 4).to(torch.float32)
439
+ num = torch.sum(W * X * c, dim=1)
440
+ den = torch.sum(W * c * c, dim=1)
441
+ valid = den > 1.0e-30
442
+ d = torch.where(valid, num / torch.where(valid, den, torch.ones_like(den)), torch.zeros_like(den))
443
+ df = d.to(torch.float16).to(torch.float32)
444
+ act = torch.abs(df) > 1.0e-15
445
+ sdf = torch.where(act, df, torch.ones_like(df))[:, None]
446
+ sh = (X / sdf) + 12582912.0
447
+ qi = ((sh.view(torch.int32) & 0x007FFFFF) - 0x00400000 + 4).clamp(0, 7)
448
+ q = torch.where(act[:, None], qi, torch.full_like(qi, 4))
449
+ e = X - df[:, None] * (q.to(torch.float32) - 4.0)
450
+ sse = torch.sum(W * e * e, dim=1)
451
+ take = sse < best_seed_sse
452
+ best_seed_sse = torch.where(take, sse, best_seed_sse)
453
+ wls_d = torch.where(take, df, wls_d)
454
+
455
+ mults = torch.tensor(MULTS_D, dtype=torch.float32, device=dev)
456
+ cand_d = (wls_d[:, None] * mults[None, :]).to(torch.float16).to(torch.float32)
457
+ act_c = torch.abs(cand_d) > 1.0e-15
458
+ sd_c = torch.where(act_c, cand_d, torch.ones_like(cand_d))[:, :, None]
459
+ sh_c = (X[:, None, :] / sd_c) + 12582912.0
460
+ qi_c = ((sh_c.view(torch.int32) & 0x007FFFFF) - 0x00400000 + 4).clamp(0, 7)
461
+ q_c = torch.where(act_c[:, :, None], qi_c, torch.full_like(qi_c, 4)).to(torch.float32)
462
+ e_c = X[:, None, :] - cand_d[:, :, None] * (q_c - 4.0)
463
+ sse_c = torch.sum(W[:, None, :] * e_c * e_c, dim=2)
464
+ if cfg.use_spectral and (lam_dc > 0.0 or lam_vw > 0.0):
465
+ v_c = e_c[:, :, :half] + e_c[:, :, half:]
466
+ dc_c = torch.sum(e_c, dim=2)
467
+ cand_err_t = sse_c + lam_vw * torch.sum(v_c * v_c, dim=2) + lam_dc * dc_c * dc_c
468
+ else:
469
+ cand_err_t = sse_c
470
+
471
+ best_cand_np = _q3_sieve_and_viterbi(cand_err_t.cpu().numpy(), cfg)
472
+ best_cand_t = torch.from_numpy(best_cand_np).to(dev)
473
+ rows = torch.arange(M, device=dev)
474
+ d_sel = cand_d[rows, best_cand_t]
475
+
476
+ rad = max(int(cfg.ulp_radius), 4)
477
+ deltas = torch.arange(-rad, rad + 1, dtype=torch.int32, device=dev)
478
+ abs_bits = torch.abs(d_sel).to(torch.float16).view(torch.int16).to(torch.int32) & 0x7FFF
479
+ pos_b = torch.clamp(abs_bits[:, None] + deltas[None, :], 0, 0x7BFF)
480
+ neg_b = pos_b | 0x8000
481
+ all_b = torch.cat([pos_b, neg_b], dim=1)
482
+ all_d = all_b.to(torch.int16).view(torch.float16).to(torch.float32)
483
+ act_u = torch.abs(all_d) > 1.0e-15
484
+ sd_u = torch.where(act_u, all_d, torch.ones_like(all_d))[:, :, None]
485
+ sh_u = (X[:, None, :] / sd_u) + 12582912.0
486
+ qi_u = ((sh_u.view(torch.int32) & 0x007FFFFF) - 0x00400000 + 4).clamp(0, 7)
487
+ q_u = torch.where(act_u[:, :, None], qi_u, torch.full_like(qi_u, 4)).to(torch.uint8)
488
+ e_u = X[:, None, :] - all_d[:, :, None] * (q_u.to(torch.float32) - 4.0)
489
+ sse_u = torch.sum(W[:, None, :] * e_u * e_u, dim=2)
490
+ pick_u = torch.argmin(sse_u, dim=1)
491
+ best_d = all_d[rows, pick_u]
492
+ best_q = q_u[rows, pick_u].to(torch.int64)
493
+
494
+ if cfg.use_spectral and (lam_vw > 0.0 or lam_dc > 0.0):
495
+ d_col = best_d[:, None]
496
+ e = X - d_col * (best_q.to(torch.float32) - 4.0)
497
+ sse_live = torch.sum(W * e * e, dim=1)
498
+ sse_cap = sse_live * (1.0 + float(cfg.sse_budget))
499
+ v = e[:, :half] + e[:, half:]
500
+ dc = torch.sum(e, dim=1)
501
+ denom = (W + lam_vw + lam_dc) * (d_col * d_col)
502
+ act_b = torch.abs(d_col) > 1.0e-15
503
+ s_den = torch.where(act_b & (denom > 1.0e-30), denom, torch.ones_like(denom))
504
+ v_full = torch.cat([v, v], dim=1)
505
+ grad = d_col * (W * e + lam_vw * v_full + lam_dc * dc[:, None])
506
+ sh_dq = (grad / s_den) + 12582912.0
507
+ dq = torch.where(
508
+ act_b,
509
+ ((sh_dq.view(torch.int32) & 0x007FFFFF) - 0x00400000).to(torch.int64),
510
+ torch.zeros_like(best_q),
511
+ )
512
+ q_new = torch.clamp(best_q + dq, 0, 7)
513
+ e_new = X - d_col * (q_new.to(torch.float32) - 4.0)
514
+ sse_new = torch.sum(W * e_new * e_new, dim=1)
515
+ v_new = e_new[:, :half] + e_new[:, half:]
516
+ dc_new = torch.sum(e_new, dim=1)
517
+ spec_old = lam_vw * torch.sum(v * v, dim=1) + lam_dc * dc * dc
518
+ spec_new = lam_vw * torch.sum(v_new * v_new, dim=1) + lam_dc * dc_new * dc_new
519
+ accept = (sse_new <= sse_cap) & ((sse_new + spec_new) < (sse_live + spec_old) - 1.0e-12)
520
+ best_q = torch.where(accept[:, None], q_new, best_q)
521
+
522
+ return best_d.cpu().numpy().astype(np.float32)
523
+
524
+
525
+ def _fit_q3_k_blocks_cuda(
526
+ X_np: np.ndarray,
527
+ W_np: np.ndarray,
528
+ sub_scales: np.ndarray,
529
+ dev: "torch.device",
530
+ cfg: HPCConfig,
531
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
532
+ """Fit GGML Q3_K super-scales and codes on CUDA."""
533
+ B = X_np.shape[0]
534
+ with torch.no_grad():
535
+ X = torch.from_numpy(X_np).to(dev, dtype=torch.float32).reshape(B, Q3_K_N_SUBBLOCKS, Q3_K_SUBBLOCK)
536
+ W = torch.from_numpy(W_np).to(dev, dtype=torch.float32).reshape(B, Q3_K_N_SUBBLOCKS, Q3_K_SUBBLOCK)
537
+ s = torch.from_numpy(sub_scales.reshape(B, Q3_K_N_SUBBLOCKS)).to(dev, dtype=torch.float32)
538
+ rows = torch.arange(B, device=dev)
539
+
540
+ max_idx = torch.argmax(torch.abs(s), dim=1)
541
+ max_scale = s[rows, max_idx]
542
+ d0 = torch.where(torch.abs(max_scale) > 1.0e-30, -max_scale / 32.0, torch.zeros_like(max_scale))
543
+ mults = torch.tensor(MULTS_D, dtype=torch.float32, device=dev)
544
+ cand_d = (d0[:, None] * mults[None, :]).to(torch.float16).to(torch.float32)
545
+ cand_bits = cand_d.to(torch.float16).view(torch.int16)
546
+
547
+ act_d = torch.abs(cand_d) > 1.0e-15
548
+ safe_d = torch.where(act_d, cand_d, torch.ones_like(cand_d))
549
+ qi = _nearest_int_t(s[:, None, :] / safe_d[:, :, None])
550
+ sc = torch.where(act_d[:, :, None], torch.clamp(qi, -32, 31), torch.zeros_like(qi))
551
+ scale = cand_d[:, :, None] * sc.to(torch.float32)
552
+ act_s = torch.abs(scale) > 1.0e-15
553
+ safe_s = torch.where(act_s, scale, torch.ones_like(scale))
554
+ cq = _nearest_int_t(X[:, None, :, :] / safe_s[:, :, :, None])
555
+ code = torch.where(act_s[:, :, :, None], torch.clamp(cq, -4, 3), torch.zeros_like(cq))
556
+ e = X[:, None, :, :] - scale[:, :, :, None] * code.to(torch.float32)
557
+ sse_c = torch.sum(W[:, None, :, :] * e * e, dim=(2, 3))
558
+
559
+ best_cand_np = _q3_sieve_and_viterbi(sse_c.cpu().numpy(), cfg)
560
+ best_cand_t = torch.from_numpy(best_cand_np).to(dev)
561
+ best_bits = cand_bits[rows, best_cand_t]
562
+
563
+ rad = max(int(cfg.ulp_radius), 4)
564
+ deltas = torch.arange(-rad, rad + 1, dtype=torch.int32, device=dev)
565
+ abs_bits = best_bits.to(torch.int32) & 0x7FFF
566
+ pos_b = torch.clamp(abs_bits[:, None] + deltas[None, :], 0, 0x7BFF)
567
+ neg_b = pos_b | 0x8000
568
+ all_b = torch.cat([pos_b, neg_b], dim=1)
569
+ all_d = all_b.to(torch.int16).view(torch.float16).to(torch.float32)
570
+ act_u = torch.abs(all_d) > 1.0e-15
571
+ safe_u = torch.where(act_u, all_d, torch.ones_like(all_d))
572
+ q_u = _nearest_int_t(s[:, None, :] / safe_u[:, :, None])
573
+ sc_u = torch.where(act_u[:, :, None], torch.clamp(q_u, -32, 31), torch.zeros_like(q_u))
574
+ scale_u = all_d[:, :, None] * sc_u.to(torch.float32)
575
+ act_su = torch.abs(scale_u) > 1.0e-15
576
+ safe_su = torch.where(act_su, scale_u, torch.ones_like(scale_u))
577
+ c_u = _nearest_int_t(X[:, None, :, :] / safe_su[:, :, :, None])
578
+ code_u = torch.where(act_su[:, :, :, None], torch.clamp(c_u, -4, 3), torch.zeros_like(c_u))
579
+ e_u = X[:, None, :, :] - scale_u[:, :, :, None] * code_u.to(torch.float32)
580
+ sse_u = torch.sum(W[:, None, :, :] * e_u * e_u, dim=(2, 3))
581
+ pick_u = torch.argmin(sse_u, dim=1)
582
+ best_d16 = all_b[rows, pick_u]
583
+ best_d = all_d[rows, pick_u]
584
+
585
+ act_b = torch.abs(best_d) > 1.0e-15
586
+ safe_b = torch.where(act_b, best_d, torch.ones_like(best_d))
587
+ sc = torch.where(
588
+ act_b[:, None],
589
+ torch.clamp(_nearest_int_t(s / safe_b[:, None]), -32, 31),
590
+ torch.zeros_like(s, dtype=torch.int32),
591
+ )
592
+ scale = best_d[:, None] * sc.to(torch.float32)
593
+ act_s = torch.abs(scale) > 1.0e-15
594
+ safe_s = torch.where(act_s, scale, torch.ones_like(scale))
595
+ code = torch.where(
596
+ act_s[:, :, None],
597
+ torch.clamp(_nearest_int_t(X / safe_s[:, :, None]), -4, 3),
598
+ torch.zeros_like(sc, dtype=torch.int32)[:, :, None].expand(B, Q3_K_N_SUBBLOCKS, Q3_K_SUBBLOCK),
599
+ )
600
+ return (
601
+ best_d16.cpu().numpy().astype(np.uint16),
602
+ sc.cpu().numpy().astype(np.int16),
603
+ code.cpu().numpy().astype(np.int16),
604
+ )
605
+
606
+
607
+ def _quantize_q3_k_hpc_cuda(
608
+ X: np.ndarray, W: np.ndarray, dev: "torch.device", cfg: HPCConfig
609
+ ) -> tuple[bytes, float]:
610
+ """Full HPC V2 Q3_K pipeline on CUDA for a chunk of (B, 256) blocks."""
611
+ B = X.shape[0]
612
+ X_f32 = X.astype(np.float32)
613
+ W_f32 = W.astype(np.float32)
614
+
615
+ sub_scales = _subblock_scales_hpc_cuda(
616
+ X_f32.reshape(B * Q3_K_N_SUBBLOCKS, Q3_K_SUBBLOCK),
617
+ W_f32.reshape(B * Q3_K_N_SUBBLOCKS, Q3_K_SUBBLOCK),
618
+ dev,
619
+ cfg,
620
+ )
621
+ d16, sc, code = _fit_q3_k_blocks_cuda(X_f32, W_f32, sub_scales, dev, cfg)
622
+
623
+ hmask, qs = _pack_q3_k_codes(code)
624
+ scales = _pack_q3_k_scales(sc)
625
+ out = np.empty((B, Q3_K_BLOCK_BYTES), dtype=np.uint8)
626
+ out[:, : QK3_K // 8] = hmask
627
+ out[:, QK3_K // 8 : QK3_K // 8 + QK3_K // 4] = qs
628
+ out[:, QK3_K // 8 + QK3_K // 4 : Q3_K_BLOCK_BYTES - 2] = scales
629
+ out[:, Q3_K_BLOCK_BYTES - 2 :] = d16.astype("<u2").view(np.uint8).reshape(B, 2)
630
+
631
+ d = from_fp16_bits(d16).astype(np.float32)
632
+ deq = (d[:, None, None] * sc[:, :, None].astype(np.float32) * code.astype(np.float32)).reshape(B, QK3_K)
633
+ raw_sse = float(np.sum((X_f32 - deq) ** 2, dtype=np.float64))
634
+ return out.tobytes(), raw_sse
635
+
636
+
637
+ def _quantize_q3_k_hpc_cpu(
638
+ X: np.ndarray, W: np.ndarray, cfg: HPCConfig
639
+ ) -> tuple[bytes, float]:
640
+ """Full HPC V2 Q3_K pipeline on CPU for a chunk of (B, 256) blocks."""
641
+ B = X.shape[0]
642
+ X_f32 = X.astype(np.float32)
643
+ W_f32 = W.astype(np.float32)
644
+
645
+ sub_scales = _subblock_scales_hpc(
646
+ X_f32.reshape(B * Q3_K_N_SUBBLOCKS, Q3_K_SUBBLOCK),
647
+ W_f32.reshape(B * Q3_K_N_SUBBLOCKS, Q3_K_SUBBLOCK),
648
+ cfg,
649
+ )
650
+ d16, sc, code = _fit_q3_k_blocks(X_f32, W_f32, sub_scales, cfg)
651
+
652
+ hmask, qs = _pack_q3_k_codes(code)
653
+ scales = _pack_q3_k_scales(sc)
654
+ out = np.empty((B, Q3_K_BLOCK_BYTES), dtype=np.uint8)
655
+ out[:, : QK3_K // 8] = hmask
656
+ out[:, QK3_K // 8 : QK3_K // 8 + QK3_K // 4] = qs
657
+ out[:, QK3_K // 8 + QK3_K // 4 : Q3_K_BLOCK_BYTES - 2] = scales
658
+ out[:, Q3_K_BLOCK_BYTES - 2 :] = d16.astype("<u2").view(np.uint8).reshape(B, 2)
659
+
660
+ d = from_fp16_bits(d16).astype(np.float32)
661
+ deq = (d[:, None, None] * sc[:, :, None].astype(np.float32) * code.astype(np.float32)).reshape(B, QK3_K)
662
+ raw_sse = float(np.sum((X_f32 - deq) ** 2, dtype=np.float64))
663
+ return out.tobytes(), raw_sse
664
+
665
+
666
+ def quantize_tensor_q3_k(
667
+ weights: np.ndarray,
668
+ importance: np.ndarray | None = None,
669
+ cfg: HPCConfig | None = None,
670
+ chunk_blocks: int = 1024,
671
+ ) -> tuple[bytes, int, float]:
672
+ """Quantize a tensor to GGML Q3_K using the full HPC V2 pipeline."""
673
+ cfg = cfg or HPCConfig()
674
+ x = np.asarray(weights, dtype=np.float32).ravel()
675
+ if x.size == 0 or x.size % QK3_K != 0:
676
+ raise ValueError("Q3_K requires a non-empty weight count divisible by 256")
677
+ n_blocks = x.size // QK3_K
678
+ X = x.reshape(n_blocks, QK3_K)
679
+
680
+ if importance is not None:
681
+ imp = np.asarray(importance, dtype=np.float32).ravel()
682
+ if imp.size != x.size:
683
+ raise ValueError("importance length must match weight count")
684
+ W_raw = imp.reshape(n_blocks, QK3_K)
685
+ else:
686
+ W_raw = None
687
+
688
+ use_cuda = cfg.device != "cpu" and torch is not None and cuda_is_available() and (
689
+ cfg.device.startswith("cuda") or (cfg.device == "auto" and n_blocks >= 64)
690
+ )
691
+ dev = torch.device("cuda" if cfg.device == "auto" else cfg.device) if use_cuda else None
692
+
693
+ chunks: list[bytes] = []
694
+ total_sse = 0.0
695
+ for start in range(0, n_blocks, chunk_blocks):
696
+ stop = min(start + chunk_blocks, n_blocks)
697
+ Xb = X[start:stop]
698
+ sig2 = np.mean(Xb * Xb, axis=1, keepdims=True)
699
+ if W_raw is None:
700
+ Wb = np.sqrt(sig2 + Xb * Xb)
701
+ else:
702
+ wr = W_raw[start:stop]
703
+ Wb = np.sqrt(np.maximum(wr, 1.0e-6)) * np.sqrt(sig2 + Xb * Xb) if cfg.temper_imatrix else wr
704
+ wm = np.mean(Wb, axis=1, keepdims=True)
705
+ Wb = np.where(wm > 1.0e-30, Wb / np.maximum(wm, 1.0e-30), 1.0).astype(np.float32)
706
+
707
+ if use_cuda and dev is not None:
708
+ raw_b, sse_b = _quantize_q3_k_hpc_cuda(Xb, Wb, dev, cfg)
709
+ else:
710
+ raw_b, sse_b = _quantize_q3_k_hpc_cpu(Xb, Wb, cfg)
711
+ chunks.append(raw_b)
712
+ total_sse += sse_b
713
+
714
+ rmse = float(np.sqrt(total_sse / x.size))
715
+ return b"".join(chunks), n_blocks, rmse