CompressedGemma commited on
Commit
22f2fee
·
verified ·
1 Parent(s): 1139e8b

Upload 6 files

Browse files
Files changed (1) hide show
  1. q3_k.py +354 -145
q3_k.py CHANGED
@@ -1,22 +1,41 @@
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
@@ -40,6 +59,10 @@ 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
 
@@ -207,6 +230,11 @@ def _q3_sieve_and_viterbi(cand_errors: np.ndarray, cfg: HPCConfig) -> np.ndarray
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:
@@ -318,91 +346,6 @@ def _subblock_scales_hpc(
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:
@@ -522,6 +465,190 @@ def _subblock_scales_hpc_cuda(
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,
@@ -529,74 +656,156 @@ def _fit_q3_k_blocks_cuda(
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),
@@ -685,7 +894,7 @@ def quantize_tensor_q3_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
 
1
+ """Full HPC V2 Q3_K quantizer (CUDA GPU + Vectorized CPU).
2
+
3
+ Implements the complete HPC-Quantize V2 decision stack for llama.cpp/GGML
4
+ ``Q3_K`` (256 weights per 110-byte block = 3.4375 bpw). The Q3_K hierarchy is
5
+ the Q4_0 pipeline applied twice:
6
+
7
+ * **Level A — 16-weight sub-blocks** (the per-sub-block scale ``s_j`` search):
8
+ runs the exact Q4_0 decision stack on every 16-weight sub-block with the
9
+ signed 3-bit grid ``[-4, +3]``:
10
+ 1. Geometry-Preserving Analog + WLS seeds (``+d`` and asymmetric ``-d``).
11
+ 2. 24-candidate scale lattice & extended spectral objective.
12
+ 3. 6-state sequential Sieve & 6-state Viterbi DP across the sub-block chain.
13
+ 4. Asymmetric sign-flip fp16-ULP polish.
14
+ 5. Closed-form 1-D quadratic Vesica + DC code projection (``sse_budget``).
15
+
16
+ * **Level B — 256-weight super-blocks** (the GGML ``(d, sc)`` fit, no
17
+ shortcuts relative to Q4_0):
18
+ 1. **Geometry-Preserving Analog + WLS Seeds** for the super-scale ``d``:
19
+ four seeds (``+max``/``-max`` grid midpoint ``/31.5`` and the iso-moment
20
+ companded analog ``+/-``), each refined by 4 rounds of weighted least
21
+ squares over the 6-bit sub-block scales with per-sub-block importance,
22
+ fp16-rounded and scored by the true 3-bit encode SSE (``+d`` and ``-d``).
23
+ 2. **24-Candidate Super-Scale Lattice & Extended Spectral Objective**:
24
+ ``cand_d = fp16(wls_d * MULTS_D)``, each candidate jointlyLS derives the
25
+ signed 6-bit scales ``sc ∈ [-32, 31]`` and 3-bit codes ``[-4, +3]`` and is
26
+ scored on importance-weighted SSE + D6/Vesica fold pyramid + DC penalty
27
+ over the full 256-weight block.
28
+ 3. **6-State Sequential Sieve & 6-State Viterbi DP** over the 24-candidate
29
+ lattice with free-energy bin reduction and greedy override.
30
+ 4. **Asymmetric Sign-Flip fp16-ULP Polish**: ``±max(ulp_radius, 4)`` fp16
31
+ ULPs around both ``+d_sel`` and ``-d_sel``, scored on exact encode SSE.
32
+ 5. **Closed-Form Vesica/DC Code Projection within ``sse_budget``**:
33
+ a bounded gradient project-and-accept step on the 3-bit codes using the
34
+ effective per-weight scale ``d*sc_j`` and the strict monotone
35
+ ``(SSE + spectral)`` decrease test.
36
+
37
+ The final ``block_q3_K`` payload is emitted in the exact GGML layout
38
+ (``hmask[32] + qs[64] + scales[12] + fp16 d``, 110 bytes).
39
  """
40
 
41
  from __future__ import annotations
 
59
  Q3_K_BLOCK_BYTES = 110
60
  Q3_K_SUBBLOCK = 16
61
  Q3_K_N_SUBBLOCKS = QK3_K // Q3_K_SUBBLOCK
62
+ Q3_SC_MIN = -32
63
+ Q3_SC_MAX = 31
64
+ Q3_CODE_MIN = -4
65
+ Q3_CODE_MAX = 3
66
  Q3_N_CAND = 24
67
  Q3_N_STATES = 6
68
 
 
230
  return np.where(g_e < cur_e * cfg.greedy_override_ratio, global_best, chosen_cand)
231
 
232
 
233
+ # ---------------------------------------------------------------------------
234
+ # Level A: HPC Q4_0 stack on 16-weight sub-blocks -> signed fp16 scales s_j
235
+ # ---------------------------------------------------------------------------
236
+
237
+
238
  def _subblock_scales_hpc(
239
  X: np.ndarray, W: np.ndarray, cfg: HPCConfig
240
  ) -> np.ndarray:
 
346
  return best_d.astype(np.float32)
347
 
348
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349
  def _subblock_scales_hpc_cuda(
350
  X_np: np.ndarray, W_np: np.ndarray, dev: "torch.device", cfg: HPCConfig
351
  ) -> np.ndarray:
 
465
  return best_d.cpu().numpy().astype(np.float32)
466
 
467
 
468
+ # ---------------------------------------------------------------------------
469
+ # Level B: GGML (d, sc, code) super-block fit — full Q4_0 decision stack
470
+ # ---------------------------------------------------------------------------
471
+
472
+
473
+ def _fit_q3_k_blocks(
474
+ X: np.ndarray, W: np.ndarray, sub_scales: np.ndarray, cfg: HPCConfig
475
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
476
+ """Full HPC V2 super-block fit for (B, 256) blocks on CPU."""
477
+ B = X.shape[0]
478
+ X3 = X.astype(np.float32).reshape(B, Q3_K_N_SUBBLOCKS, Q3_K_SUBBLOCK)
479
+ W3 = W.astype(np.float32).reshape(B, Q3_K_N_SUBBLOCKS, Q3_K_SUBBLOCK)
480
+ Xf = X3.reshape(B, QK3_K)
481
+ Wf = W3.reshape(B, QK3_K)
482
+ s = sub_scales.reshape(B, Q3_K_N_SUBBLOCKS).astype(np.float32)
483
+ rows = np.arange(B)
484
+ lam_dc = (float(cfg.dc_lambda) / QK3_K) if cfg.use_spectral else 0.0
485
+ lam_vw = (float(cfg.vw_lambda) / QK3_K) if cfg.use_spectral else 0.0
486
+ Wj = W3.sum(axis=2) # (B, 16) per-sub-block importance
487
+
488
+ def _encode(d: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
489
+ """JointLS quantize s with scale d: sc in [-32,31], codes in [-4,3]."""
490
+ act = np.abs(d) > 1.0e-15
491
+ safe_d = np.where(act, d, 1.0)
492
+ sc = np.where(
493
+ act[:, None],
494
+ np.clip(nearest_int((s / safe_d[:, None]).astype(np.float32)), Q3_SC_MIN, Q3_SC_MAX),
495
+ 0,
496
+ )
497
+ scale = d[:, None] * sc.astype(np.float32)
498
+ act_s = np.abs(scale) > 1.0e-15
499
+ safe_s = np.where(act_s, scale, 1.0)
500
+ code = np.where(
501
+ act_s[:, :, None],
502
+ np.clip(nearest_int((X3 / safe_s[:, :, None]).astype(np.float32)), Q3_CODE_MIN, Q3_CODE_MAX),
503
+ 0,
504
+ )
505
+ e = X3 - scale[:, :, None] * code.astype(np.float32)
506
+ sse = np.sum(W3 * e * e, axis=(1, 2), dtype=np.float64)
507
+ return sc, code, sse
508
+
509
+ # 1. Geometry-Preserving Analog + WLS Seeds for the super-scale d:
510
+ amax = np.max(np.abs(s), axis=1)
511
+ d_range = amax / 31.5
512
+ wsum = np.maximum(np.sum(Wj, axis=1, keepdims=True), 1.0e-30)
513
+ mu = np.sum(Wj * s, axis=1, keepdims=True) / wsum
514
+ var = np.sum(Wj * (s - mu) ** 2, axis=1, keepdims=True) / wsum
515
+ sig = np.sqrt(np.maximum(var, 1.0e-30))
516
+ s_comp = mu + sig * 1.85 * np.tanh((s - mu) / (1.85 * sig))
517
+ d_analog = (np.max(np.abs(s_comp), axis=1) / 31.5).astype(np.float32)
518
+
519
+ wls_d = d_range.copy()
520
+ best_seed_sse = np.full(B, np.inf, dtype=np.float64)
521
+ for d_start in (d_range, -d_range, d_analog, -d_analog):
522
+ d = d_start.astype(np.float64)
523
+ for _ in range(4):
524
+ act = np.abs(d) > 1.0e-15
525
+ sd = np.where(act, d, 1.0)[:, None]
526
+ sc = np.where(
527
+ act[:, None],
528
+ np.clip(nearest_int((s / sd).astype(np.float32)), Q3_SC_MIN, Q3_SC_MAX),
529
+ 0,
530
+ )
531
+ c = sc.astype(np.float64)
532
+ num = np.sum(Wj * s * c, axis=1, dtype=np.float64)
533
+ den = np.sum(Wj * c * c, axis=1, dtype=np.float64)
534
+ valid = den > 1.0e-30
535
+ d = np.where(valid, num / np.where(valid, den, 1.0), 0.0)
536
+ df = from_fp16_bits(to_fp16_bits(d.astype(np.float32)))
537
+ _, _, sse = _encode(df)
538
+ take = sse < best_seed_sse
539
+ best_seed_sse = np.where(take, sse, best_seed_sse)
540
+ wls_d = np.where(take, df, wls_d)
541
+
542
+ # 2. 24-Candidate Super-Scale Lattice with Extended Spectral Objective:
543
+ cand_d16 = to_fp16_bits(wls_d[:, None] * MULTS_D[None, :]) # (B, 24)
544
+ cand_d = from_fp16_bits(cand_d16)
545
+ act_c = np.abs(cand_d) > 1.0e-15
546
+ safe_c = np.where(act_c, cand_d, 1.0)
547
+ sc_c = np.where(
548
+ act_c[:, :, None],
549
+ np.clip(nearest_int((s[:, None, :] / safe_c[:, :, None]).astype(np.float32)), Q3_SC_MIN, Q3_SC_MAX),
550
+ 0,
551
+ )
552
+ scale_c = cand_d[:, :, None] * sc_c.astype(np.float32) # (B, 24, 16)
553
+ act_s = np.abs(scale_c) > 1.0e-15
554
+ safe_s = np.where(act_s, scale_c, 1.0)
555
+ code_c = np.where(
556
+ act_s[:, :, :, None],
557
+ np.clip(nearest_int((X3[:, None] / safe_s[:, :, :, None]).astype(np.float32)), Q3_CODE_MIN, Q3_CODE_MAX),
558
+ 0,
559
+ ).astype(np.int16)
560
+ e_f = (X3[:, None] - scale_c[:, :, :, None] * code_c.astype(np.float32)).reshape(B, Q3_N_CAND, QK3_K)
561
+ sse_c = np.sum(Wf[:, None, :] * e_f * e_f, axis=2)
562
+ if cfg.use_spectral and (lam_dc > 0.0 or lam_vw > 0.0):
563
+ half = QK3_K // 2
564
+ v_c = e_f[:, :, :half] + e_f[:, :, half:]
565
+ dc_c = np.sum(e_f, axis=2)
566
+ cand_errors = (sse_c + lam_vw * np.sum(v_c * v_c, axis=2) + lam_dc * dc_c * dc_c).astype(np.float32)
567
+ else:
568
+ cand_errors = sse_c.astype(np.float32)
569
+
570
+ # 3. 6-State Sieve + 6-State Viterbi DP over the super-scale lattice:
571
+ best_cand = _q3_sieve_and_viterbi(cand_errors, cfg)
572
+ d_sel = cand_d[rows, best_cand]
573
+
574
+ # 4. Asymmetric Sign-Flip fp16-ULP Polish (+/-8 ULPs around +d_sel and -d_sel):
575
+ rad = max(int(cfg.ulp_radius), 4)
576
+ deltas = np.arange(-rad, rad + 1, dtype=np.int32)
577
+ pos_b = np.clip(
578
+ to_fp16_bits(np.abs(d_sel)).astype(np.int32)[:, None] + deltas[None, :],
579
+ 0,
580
+ 0x7BFF,
581
+ ).astype(np.uint16)
582
+ neg_b = (pos_b | np.uint16(0x8000)).astype(np.uint16)
583
+ all_b = np.concatenate([pos_b, neg_b], axis=1)
584
+ all_d = from_fp16_bits(all_b)
585
+ act_u = np.abs(all_d) > 1.0e-15
586
+ safe_u = np.where(act_u, all_d, 1.0)
587
+ sc_u = np.where(
588
+ act_u[:, :, None],
589
+ np.clip(nearest_int((s[:, None, :] / safe_u[:, :, None]).astype(np.float32)), Q3_SC_MIN, Q3_SC_MAX),
590
+ 0,
591
+ )
592
+ scale_u = all_d[:, :, None] * sc_u.astype(np.float32)
593
+ act_su = np.abs(scale_u) > 1.0e-15
594
+ safe_su = np.where(act_su, scale_u, 1.0)
595
+ code_u = np.where(
596
+ act_su[:, :, :, None],
597
+ np.clip(nearest_int((X3[:, None] / safe_su[:, :, :, None]).astype(np.float32)), Q3_CODE_MIN, Q3_CODE_MAX),
598
+ 0,
599
+ )
600
+ e_u = X3[:, None] - scale_u[:, :, :, None] * code_u.astype(np.float32)
601
+ sse_u = np.sum(W3[:, None] * e_u * e_u, axis=(2, 3), dtype=np.float64)
602
+ pick_u = np.argmin(sse_u, axis=1)
603
+ best_d16 = all_b[rows, pick_u]
604
+ best_d = all_d[rows, pick_u]
605
+
606
+ # Final (sc, code) derived from the polished super-scale d:
607
+ act_b = np.abs(best_d) > 1.0e-15
608
+ safe_b = np.where(act_b, best_d, 1.0)
609
+ sc = np.where(
610
+ act_b[:, None],
611
+ np.clip(nearest_int((s / safe_b[:, None]).astype(np.float32)), Q3_SC_MIN, Q3_SC_MAX),
612
+ 0,
613
+ )
614
+ scale = best_d[:, None] * sc.astype(np.float32)
615
+ act_s = np.abs(scale) > 1.0e-15
616
+ safe_s = np.where(act_s, scale, 1.0)
617
+ code = np.where(
618
+ act_s[:, :, None],
619
+ np.clip(nearest_int((X3 / safe_s[:, :, None]).astype(np.float32)), Q3_CODE_MIN, Q3_CODE_MAX),
620
+ 0,
621
+ )
622
+
623
+ # 5. Closed-Form 1-D Quadratic Vesica + DC Code Projection within sse_budget:
624
+ if cfg.use_spectral and (lam_vw > 0.0 or lam_dc > 0.0):
625
+ d_w = np.repeat(best_d[:, None].astype(np.float64) * sc.astype(np.float64), Q3_K_SUBBLOCK, axis=1)
626
+ e = Xf.astype(np.float64) - d_w * code.reshape(B, QK3_K)
627
+ sse_live = np.sum(Wf * e * e, axis=1, dtype=np.float64)
628
+ sse_cap = sse_live * (1.0 + cfg.sse_budget)
629
+ half = QK3_K // 2
630
+ v = e[:, :half] + e[:, half:]
631
+ dc = np.sum(e, axis=1)
632
+ denom = (Wf + lam_vw + lam_dc) * (d_w * d_w)
633
+ act_bw = np.abs(d_w) > 1.0e-15
634
+ s_den = np.where(act_bw & (denom > 1.0e-30), denom, 1.0)
635
+ v_full = np.concatenate([v, v], axis=1)
636
+ grad = d_w * (Wf * e + lam_vw * v_full + lam_dc * dc[:, None])
637
+ dq = np.where(act_bw, nearest_int((grad / s_den).astype(np.float32)), 0)
638
+ code_f = code.reshape(B, QK3_K)
639
+ code_new = np.clip(code_f + dq, Q3_CODE_MIN, Q3_CODE_MAX)
640
+ e_new = Xf.astype(np.float64) - d_w * code_new
641
+ sse_new = np.sum(Wf * e_new * e_new, axis=1, dtype=np.float64)
642
+ v_new = e_new[:, :half] + e_new[:, half:]
643
+ dc_new = np.sum(e_new, axis=1)
644
+ spec_old = lam_vw * np.sum(v * v, axis=1) + lam_dc * dc * dc
645
+ spec_new = lam_vw * np.sum(v_new * v_new, axis=1) + lam_dc * dc_new * dc_new
646
+ accept = (sse_new <= sse_cap) & ((sse_new + spec_new) < (sse_live + spec_old) - 1.0e-15)
647
+ code = np.where(accept[:, None], code_new, code_f).reshape(B, Q3_K_N_SUBBLOCKS, Q3_K_SUBBLOCK)
648
+
649
+ return best_d16.astype(np.uint16), sc.astype(np.int16), code.astype(np.int16)
650
+
651
+
652
  def _fit_q3_k_blocks_cuda(
653
  X_np: np.ndarray,
654
  W_np: np.ndarray,
 
656
  dev: "torch.device",
657
  cfg: HPCConfig,
658
  ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
659
+ """Full HPC V2 super-block fit for (B, 256) blocks on CUDA."""
660
  B = X_np.shape[0]
661
+ lam_dc = (float(cfg.dc_lambda) / QK3_K) if cfg.use_spectral else 0.0
662
+ lam_vw = (float(cfg.vw_lambda) / QK3_K) if cfg.use_spectral else 0.0
663
+
664
  with torch.no_grad():
665
+ X3 = torch.from_numpy(X_np).to(dev, dtype=torch.float32).reshape(B, Q3_K_N_SUBBLOCKS, Q3_K_SUBBLOCK)
666
+ W3 = torch.from_numpy(W_np).to(dev, dtype=torch.float32).reshape(B, Q3_K_N_SUBBLOCKS, Q3_K_SUBBLOCK)
667
+ Xf = X3.reshape(B, QK3_K)
668
+ Wf = W3.reshape(B, QK3_K)
669
+ s = torch.from_numpy(np.ascontiguousarray(sub_scales.reshape(B, Q3_K_N_SUBBLOCKS))).to(dev, dtype=torch.float32)
670
  rows = torch.arange(B, device=dev)
671
+ Wj = W3.sum(dim=2) # (B, 16) per-sub-block importance
672
+
673
+ def _encode(d: "torch.Tensor"):
674
+ """JointLS quantize s with scale d: sc in [-32,31], codes in [-4,3]."""
675
+ act = torch.abs(d) > 1.0e-15
676
+ safe_d = torch.where(act, d, torch.ones_like(d))
677
+ q_sc = _nearest_int_t(s / safe_d[:, None]).clamp(Q3_SC_MIN, Q3_SC_MAX)
678
+ sc = torch.where(act[:, None], q_sc, torch.zeros_like(q_sc))
679
+ scale = d[:, None] * sc.to(torch.float32)
680
+ act_s = torch.abs(scale) > 1.0e-15
681
+ safe_s = torch.where(act_s, scale, torch.ones_like(scale))
682
+ q_cd = _nearest_int_t(X3 / safe_s[:, :, None]).clamp(Q3_CODE_MIN, Q3_CODE_MAX)
683
+ code = torch.where(act_s[:, :, None], q_cd, torch.zeros_like(q_cd))
684
+ e = X3 - scale[:, :, None] * code.to(torch.float32)
685
+ sse = torch.sum(W3 * e * e, dim=(1, 2))
686
+ return sc, code, sse
687
+
688
+ # 1. Geometry-Preserving Analog + WLS Seeds for the super-scale d:
689
+ amax = torch.max(torch.abs(s), dim=1).values
690
+ d_range = amax / 31.5
691
+ wsum = torch.clamp(torch.sum(Wj, dim=1, keepdim=True), min=1.0e-30)
692
+ mu = torch.sum(Wj * s, dim=1, keepdim=True) / wsum
693
+ var = torch.sum(Wj * (s - mu) ** 2, dim=1, keepdim=True) / wsum
694
+ sig = torch.sqrt(torch.clamp(var, min=1.0e-30))
695
+ s_comp = mu + sig * 1.85 * torch.tanh((s - mu) / (1.85 * sig))
696
+ d_analog = torch.max(torch.abs(s_comp), dim=1).values / 31.5
697
+
698
+ wls_d = d_range.clone()
699
+ best_seed_sse = torch.full((B,), float("inf"), dtype=torch.float32, device=dev)
700
+ for d_start in (d_range, -d_range, d_analog, -d_analog):
701
+ d = d_start.clone()
702
+ for _ in range(4):
703
+ act = torch.abs(d) > 1.0e-15
704
+ sd = torch.where(act, d, torch.ones_like(d))[:, None]
705
+ qi = _nearest_int_t(s / sd).clamp(Q3_SC_MIN, Q3_SC_MAX)
706
+ sc = torch.where(act[:, None], qi, torch.zeros_like(qi))
707
+ c = sc.to(torch.float32)
708
+ num = torch.sum(Wj * s * c, dim=1)
709
+ den = torch.sum(Wj * c * c, dim=1)
710
+ valid = den > 1.0e-30
711
+ d = torch.where(valid, num / torch.where(valid, den, torch.ones_like(den)), torch.zeros_like(den))
712
+ df = d.to(torch.float16).to(torch.float32)
713
+ _, _, sse = _encode(df)
714
+ take = sse < best_seed_sse
715
+ best_seed_sse = torch.where(take, sse, best_seed_sse)
716
+ wls_d = torch.where(take, df, wls_d)
717
 
718
+ # 2. 24-Candidate Super-Scale Lattice with Extended Spectral Objective:
 
 
719
  mults = torch.tensor(MULTS_D, dtype=torch.float32, device=dev)
720
+ cand_d = (wls_d[:, None] * mults[None, :]).to(torch.float16).to(torch.float32)
721
+ act_c = torch.abs(cand_d) > 1.0e-15
722
+ safe_c = torch.where(act_c, cand_d, torch.ones_like(cand_d))
723
+ q_sc_c = _nearest_int_t(s[:, None, :] / safe_c[:, :, None]).clamp(Q3_SC_MIN, Q3_SC_MAX)
724
+ sc_c = torch.where(act_c[:, :, None], q_sc_c, torch.zeros_like(q_sc_c))
725
+ scale_c = cand_d[:, :, None] * sc_c.to(torch.float32)
726
+ act_s = torch.abs(scale_c) > 1.0e-15
727
+ safe_s = torch.where(act_s, scale_c, torch.ones_like(scale_c))
728
+ q_cd_c = _nearest_int_t(X3[:, None] / safe_s[:, :, :, None]).clamp(Q3_CODE_MIN, Q3_CODE_MAX)
729
+ code_c = torch.where(act_s[:, :, :, None], q_cd_c, torch.zeros_like(q_cd_c))
730
+ e_f = (X3[:, None] - scale_c[:, :, :, None] * code_c.to(torch.float32)).reshape(B, Q3_N_CAND, QK3_K)
731
+ sse_c = torch.sum(Wf[:, None, :] * e_f * e_f, dim=2)
732
+ if cfg.use_spectral and (lam_dc > 0.0 or lam_vw > 0.0):
733
+ half = QK3_K // 2
734
+ v_c = e_f[:, :, :half] + e_f[:, :, half:]
735
+ dc_c = torch.sum(e_f, dim=2)
736
+ cand_err_t = sse_c + lam_vw * torch.sum(v_c * v_c, dim=2) + lam_dc * dc_c * dc_c
737
+ else:
738
+ cand_err_t = sse_c
739
 
740
+ # 3. 6-State Sieve + 6-State Viterbi DP over the super-scale lattice:
741
+ best_cand_np = _q3_sieve_and_viterbi(cand_err_t.cpu().numpy(), cfg)
742
  best_cand_t = torch.from_numpy(best_cand_np).to(dev)
743
+ d_sel = cand_d[rows, best_cand_t]
744
 
745
+ # 4. Asymmetric Sign-Flip fp16-ULP Polish (+/-8 ULPs around +d_sel and -d_sel):
746
  rad = max(int(cfg.ulp_radius), 4)
747
  deltas = torch.arange(-rad, rad + 1, dtype=torch.int32, device=dev)
748
+ abs_bits = torch.abs(d_sel).to(torch.float16).view(torch.int16).to(torch.int32) & 0x7FFF
749
  pos_b = torch.clamp(abs_bits[:, None] + deltas[None, :], 0, 0x7BFF)
750
  neg_b = pos_b | 0x8000
751
  all_b = torch.cat([pos_b, neg_b], dim=1)
752
  all_d = all_b.to(torch.int16).view(torch.float16).to(torch.float32)
753
  act_u = torch.abs(all_d) > 1.0e-15
754
  safe_u = torch.where(act_u, all_d, torch.ones_like(all_d))
755
+ q_sc_u = _nearest_int_t(s[:, None, :] / safe_u[:, :, None]).clamp(Q3_SC_MIN, Q3_SC_MAX)
756
+ sc_u = torch.where(act_u[:, :, None], q_sc_u, torch.zeros_like(q_sc_u))
757
  scale_u = all_d[:, :, None] * sc_u.to(torch.float32)
758
  act_su = torch.abs(scale_u) > 1.0e-15
759
  safe_su = torch.where(act_su, scale_u, torch.ones_like(scale_u))
760
+ q_cd_u = _nearest_int_t(X3[:, None] / safe_su[:, :, :, None]).clamp(Q3_CODE_MIN, Q3_CODE_MAX)
761
+ code_u = torch.where(act_su[:, :, :, None], q_cd_u, torch.zeros_like(q_cd_u))
762
+ e_u = X3[:, None] - scale_u[:, :, :, None] * code_u.to(torch.float32)
763
+ sse_u = torch.sum(W3[:, None] * e_u * e_u, dim=(2, 3))
764
  pick_u = torch.argmin(sse_u, dim=1)
765
  best_d16 = all_b[rows, pick_u]
766
  best_d = all_d[rows, pick_u]
767
 
768
+ # Final (sc, code) derived from the polished super-scale d:
769
  act_b = torch.abs(best_d) > 1.0e-15
770
  safe_b = torch.where(act_b, best_d, torch.ones_like(best_d))
771
+ q_bs = _nearest_int_t(s / safe_b[:, None]).clamp(Q3_SC_MIN, Q3_SC_MAX)
772
+ sc = torch.where(act_b[:, None], q_bs, torch.zeros_like(q_bs))
 
 
 
773
  scale = best_d[:, None] * sc.to(torch.float32)
774
  act_s = torch.abs(scale) > 1.0e-15
775
  safe_s = torch.where(act_s, scale, torch.ones_like(scale))
776
+ q_bd = _nearest_int_t(X3 / safe_s[:, :, None]).clamp(Q3_CODE_MIN, Q3_CODE_MAX)
777
+ code = torch.where(act_s[:, :, None], q_bd, torch.zeros_like(q_bd))
778
+ code_f = code.reshape(B, QK3_K)
779
+
780
+ # 5. Closed-Form Vesica/DC Code Projection within sse_budget:
781
+ if cfg.use_spectral and (lam_vw > 0.0 or lam_dc > 0.0):
782
+ d_w = (best_d[:, None] * sc.to(torch.float32)).repeat_interleave(Q3_K_SUBBLOCK, dim=1)
783
+ e_f64 = Xf - d_w * code_f.to(torch.float32)
784
+ sse_live = torch.sum(Wf * e_f64 * e_f64, dim=1)
785
+ sse_cap = sse_live * (1.0 + float(cfg.sse_budget))
786
+ half = QK3_K // 2
787
+ v = e_f64[:, :half] + e_f64[:, half:]
788
+ dc = torch.sum(e_f64, dim=1)
789
+ denom = (Wf + lam_vw + lam_dc) * (d_w * d_w)
790
+ act_bw = torch.abs(d_w) > 1.0e-15
791
+ s_den = torch.where(act_bw & (denom > 1.0e-30), denom, torch.ones_like(denom))
792
+ v_full = torch.cat([v, v], dim=1)
793
+ grad = d_w * (Wf * e_f64 + lam_vw * v_full + lam_dc * dc[:, None])
794
+ dq = torch.where(
795
+ act_bw,
796
+ _nearest_int_t(grad / s_den),
797
+ torch.zeros_like(code_f),
798
+ )
799
+ code_new = torch.clamp(code_f + dq, Q3_CODE_MIN, Q3_CODE_MAX)
800
+ e_new = Xf - d_w * code_new.to(torch.float32)
801
+ sse_new = torch.sum(Wf * e_new * e_new, dim=1)
802
+ v_new = e_new[:, :half] + e_new[:, half:]
803
+ dc_new = torch.sum(e_new, dim=1)
804
+ spec_old = lam_vw * torch.sum(v * v, dim=1) + lam_dc * dc * dc
805
+ spec_new = lam_vw * torch.sum(v_new * v_new, dim=1) + lam_dc * dc_new * dc_new
806
+ accept = (sse_new <= sse_cap) & ((sse_new + spec_new) < (sse_live + spec_old) - 1.0e-12)
807
+ code = torch.where(accept[:, None], code_new, code_f).reshape(B, Q3_K_N_SUBBLOCKS, Q3_K_SUBBLOCK)
808
+
809
  return (
810
  best_d16.cpu().numpy().astype(np.uint16),
811
  sc.cpu().numpy().astype(np.int16),
 
894
  else:
895
  W_raw = None
896
 
897
+ use_cuda = cfg.device != "cpu" and cuda_is_available() and (
898
  cfg.device.startswith("cuda") or (cfg.device == "auto" and n_blocks >= 64)
899
  )
900
  dev = torch.device("cuda" if cfg.device == "auto" else cfg.device) if use_cuda else None