Exploit the factorization of codes
Browse files- smq_qat.py +518 -311
smq_qat.py
CHANGED
|
@@ -203,16 +203,14 @@ class SmqImatrix:
|
|
| 203 |
return None
|
| 204 |
|
| 205 |
|
| 206 |
-
def
|
| 207 |
-
W
|
| 208 |
-
importance=None,
|
| 209 |
-
) -> np.ndarray:
|
| 210 |
-
"""Run the real SMQ quantizer on *W* and return the dequantized weights.
|
| 211 |
|
| 212 |
W: (rows, cols) float32 with cols % 256 == 0 (blocks run along the input
|
| 213 |
axis, exactly as the converter packs them). ``importance`` is whatever
|
| 214 |
``factorize_q2k`` accepts: None, a per-block (n, 256) array, or a
|
| 215 |
-
FullWeights / ChannelWeights object.
|
|
|
|
| 216 |
"""
|
| 217 |
W = np.ascontiguousarray(W, dtype=np.float32)
|
| 218 |
rows, cols = W.shape
|
|
@@ -226,8 +224,23 @@ def quantize_dequantize(
|
|
| 226 |
rtn_baseline=True,
|
| 227 |
weights=importance,
|
| 228 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
rec = smqc.unpack_q2k_blocks_for_test(packed) # (n_blocks, 256), bit-exact
|
| 230 |
-
return np.ascontiguousarray(rec.reshape(rows, cols), dtype=np.float32)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
|
| 232 |
|
| 233 |
def quantize_dequantize_torch(
|
|
@@ -235,7 +248,8 @@ def quantize_dequantize_torch(
|
|
| 235 |
importance=None,
|
| 236 |
device=None,
|
| 237 |
round_dtype: "torch.dtype | None" = None,
|
| 238 |
-
|
|
|
|
| 239 |
"""Fake-quant *W* with the real SMQ quantizer (numpy engine, CPU).
|
| 240 |
|
| 241 |
The full-precision weight crosses to the CPU, SMQ quantizes + decodes it
|
|
@@ -244,8 +258,9 @@ def quantize_dequantize_torch(
|
|
| 244 |
no torch kernels, so this is the faithful round-trip.
|
| 245 |
|
| 246 |
``round_dtype`` first rounds *W* onto the storage lattice the export uses
|
| 247 |
-
(``torch.float16`` for trained 2-D projections), so
|
| 248 |
-
same values the converter will actually quantize.
|
|
|
|
| 249 |
"""
|
| 250 |
if round_dtype is not None:
|
| 251 |
# Round on the GPU, transfer the *half-size* payload, and widen on the
|
|
@@ -253,9 +268,12 @@ def quantize_dequantize_torch(
|
|
| 253 |
arr = W.detach().to(round_dtype).cpu().numpy().astype(np.float32, copy=False)
|
| 254 |
else:
|
| 255 |
arr = W.detach().float().cpu().numpy()
|
| 256 |
-
|
| 257 |
-
|
|
|
|
|
|
|
| 258 |
device=W.device if device is None else device, dtype=W.dtype)
|
|
|
|
| 259 |
|
| 260 |
|
| 261 |
class QatWeight(nn.Module):
|
|
@@ -264,7 +282,8 @@ class QatWeight(nn.Module):
|
|
| 264 |
def __init__(self, importance=None, offload: bool = False,
|
| 265 |
round_dtype: "torch.dtype | None" = None,
|
| 266 |
cache_device: bool | None = None,
|
| 267 |
-
cache_error: bool = False
|
|
|
|
| 268 |
super().__init__()
|
| 269 |
self.importance = importance
|
| 270 |
self.offload = offload # keep the decoded cache in (pinned) CPU RAM
|
|
@@ -274,6 +293,8 @@ class QatWeight(nn.Module):
|
|
| 274 |
# decoded weights are not being offloaded.
|
| 275 |
self.cache_device = (not offload) if cache_device is None else bool(cache_device)
|
| 276 |
self.q = None
|
|
|
|
|
|
|
| 277 |
self.err = None # Q(W_ref) - W_ref, forward = W + err
|
| 278 |
self._dev_q = None
|
| 279 |
self._dev_err = None
|
|
@@ -324,8 +345,10 @@ class QatWeight(nn.Module):
|
|
| 324 |
def refresh(self, W: "torch.Tensor") -> None:
|
| 325 |
"""Re-quantize *W* with the real SMQ engine and cache the decoded copy."""
|
| 326 |
if self.offload:
|
| 327 |
-
q = quantize_dequantize_torch(
|
| 328 |
-
W, self.importance, device="cpu", round_dtype=self.round_dtype
|
|
|
|
|
|
|
| 329 |
if self.cache_error:
|
| 330 |
# err is relative to the fp32 W on its device, computed there
|
| 331 |
# once per refresh (not once per forward), then pinned for H2D.
|
|
@@ -341,8 +364,9 @@ class QatWeight(nn.Module):
|
|
| 341 |
pass
|
| 342 |
self.q = q
|
| 343 |
else:
|
| 344 |
-
self.q = quantize_dequantize_torch(
|
| 345 |
-
W, self.importance, round_dtype=self.round_dtype)
|
|
|
|
| 346 |
self.err = (self.q - W) if self.cache_error else None
|
| 347 |
self._dev_q = None
|
| 348 |
self._dev_err = None
|
|
@@ -361,7 +385,9 @@ class QatManager:
|
|
| 361 |
round_dtype: "torch.dtype | None" = None,
|
| 362 |
max_workers: int | None = None,
|
| 363 |
cache_error: bool = False,
|
| 364 |
-
track_drift: bool = False
|
|
|
|
|
|
|
| 365 |
self.offload_q = offload_q
|
| 366 |
self.round_dtype = round_dtype
|
| 367 |
# SMQ is numpy + per-tensor; independent tensors quantize in parallel.
|
|
@@ -382,7 +408,8 @@ class QatManager:
|
|
| 382 |
self.names.append(name or f"module{len(self.modules) - 1}")
|
| 383 |
return True
|
| 384 |
qw = QatWeight(importance, self.offload_q, self.round_dtype,
|
| 385 |
-
cache_error=self.cache_error
|
|
|
|
| 386 |
qw._defer = True
|
| 387 |
try:
|
| 388 |
P.register_parametrization(module, "weight", qw)
|
|
@@ -1857,56 +1884,202 @@ class _WindowWeights:
|
|
| 1857 |
return self.inner.chunk(self.off + c0, self.off + c1, qk)
|
| 1858 |
|
| 1859 |
|
| 1860 |
-
|
| 1861 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1862 |
|
| 1863 |
-
|
| 1864 |
-
|
| 1865 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1866 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1867 |
|
| 1868 |
-
def __init__(self):
|
| 1869 |
-
self._term = None
|
| 1870 |
-
self._fd = -1
|
| 1871 |
-
try:
|
| 1872 |
-
import termios
|
| 1873 |
-
import tty
|
| 1874 |
-
|
| 1875 |
-
fd = sys.stdin.fileno()
|
| 1876 |
-
if not sys.stdin.isatty():
|
| 1877 |
-
return
|
| 1878 |
-
saved = termios.tcgetattr(fd)
|
| 1879 |
-
tty.setcbreak(fd)
|
| 1880 |
-
self._fd = fd
|
| 1881 |
-
self._saved = saved
|
| 1882 |
-
self._term = termios
|
| 1883 |
-
except Exception: # noqa: BLE001 - no controlling terminal
|
| 1884 |
-
self._term = None
|
| 1885 |
-
|
| 1886 |
-
def pressed(self) -> bool:
|
| 1887 |
-
if self._term is None:
|
| 1888 |
-
return False
|
| 1889 |
-
import select
|
| 1890 |
|
| 1891 |
-
|
| 1892 |
-
|
| 1893 |
-
if not ready:
|
| 1894 |
-
return False
|
| 1895 |
-
return os.read(self._fd, 1) == b" "
|
| 1896 |
-
except OSError:
|
| 1897 |
-
return False
|
| 1898 |
|
| 1899 |
-
@property
|
| 1900 |
-
def enabled(self) -> bool:
|
| 1901 |
-
return self._term is not None
|
| 1902 |
|
| 1903 |
-
|
| 1904 |
-
|
| 1905 |
-
|
| 1906 |
-
|
| 1907 |
-
|
| 1908 |
-
|
| 1909 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1910 |
|
| 1911 |
|
| 1912 |
class BlockQatTrainer:
|
|
@@ -1946,6 +2119,9 @@ class BlockQatTrainer:
|
|
| 1946 |
seed: int = 0,
|
| 1947 |
verbose: bool = False,
|
| 1948 |
log=print,
|
|
|
|
|
|
|
|
|
|
| 1949 |
):
|
| 1950 |
self.reader = reader
|
| 1951 |
self.imat = imat
|
|
@@ -1966,7 +2142,10 @@ class BlockQatTrainer:
|
|
| 1966 |
self.warmup_frac = max(0.0, float(warmup_frac))
|
| 1967 |
self.round_dtype = torch.float16 if (fp16_round and torch is not None) else None
|
| 1968 |
self.fresh_penalty = fresh_penalty
|
| 1969 |
-
self.cache_quant_error =
|
|
|
|
|
|
|
|
|
|
| 1970 |
self.requant_drift = max(0.0, float(requant_drift))
|
| 1971 |
self.drift_check_every = max(1, int(drift_check_every))
|
| 1972 |
# 0 = automatic cadence (steps // 10, capped at 10 for adaptive runs).
|
|
@@ -2021,8 +2200,8 @@ class BlockQatTrainer:
|
|
| 2021 |
def _attached(self, model, block: int):
|
| 2022 |
manager = QatManager(
|
| 2023 |
offload_q=self._offload_q_now, round_dtype=self.round_dtype,
|
| 2024 |
-
max_workers=self.quant_workers, cache_error=
|
| 2025 |
-
track_drift=
|
| 2026 |
layer = _get_decoder_layers(model)[0]
|
| 2027 |
for gguf_name, hf_name in self._trainable(block):
|
| 2028 |
try:
|
|
@@ -2062,40 +2241,29 @@ class BlockQatTrainer:
|
|
| 2062 |
return n
|
| 2063 |
|
| 2064 |
def _plan_memory(self, block: int) -> bool:
|
| 2065 |
-
"""
|
| 2066 |
|
| 2067 |
-
Per trainable parameter (fp32): weight 4 +
|
| 2068 |
-
|
|
|
|
|
|
|
| 2069 |
"""
|
| 2070 |
if self.device.type != "cuda":
|
| 2071 |
return False
|
| 2072 |
gib = 2 ** 30
|
| 2073 |
n = self._est_trainable_params(block)
|
| 2074 |
free, _total = torch.cuda.mem_get_info(self.device)
|
| 2075 |
-
|
| 2076 |
-
if isinstance(mode, str):
|
| 2077 |
-
mode = {"on": True, "true": True, "off": False, "false": False}.get(mode.lower(), "auto")
|
| 2078 |
-
auto_per = 26 if self.cache_quant_error else 22
|
| 2079 |
-
off = (auto_per * n + 3 * gib > free) if mode == "auto" else bool(mode)
|
| 2080 |
-
per = 18 if off else 22
|
| 2081 |
-
if self.cache_quant_error and not off:
|
| 2082 |
-
per += 4 # cached quantization error lives on the GPU too
|
| 2083 |
-
need = per * n
|
| 2084 |
self.log(
|
| 2085 |
-
f"blk.{block}: {n / 1e6:.0f}M trainable params -> ~{need / gib:.1f} GiB
|
| 2086 |
-
f"(+ activations) vs {free / gib:.1f} GiB free
|
| 2087 |
-
f"{'CPU (offloaded)' if off else 'GPU'}"
|
| 2088 |
)
|
| 2089 |
-
if self.cache_quant_error and off:
|
| 2090 |
-
self.log(
|
| 2091 |
-
f"blk.{block}: error cache adds ~{4 * n / gib:.1f} GiB of pinned host RAM "
|
| 2092 |
-
"(kept alongside the decoded weights)")
|
| 2093 |
if need + gib > free:
|
| 2094 |
self.log(
|
| 2095 |
f"blk.{block}: WARNING: likely to run out of VRAM; consider a smaller "
|
| 2096 |
-
"micro_batch
|
| 2097 |
)
|
| 2098 |
-
return
|
| 2099 |
|
| 2100 |
def train_block(self, block: int, h: "_ActivationBuffer", hf_dir: Path) -> "_ActivationBuffer":
|
| 2101 |
"""Train one block; returns the activations to feed the next block."""
|
|
@@ -2136,7 +2304,7 @@ class BlockQatTrainer:
|
|
| 2136 |
torch.cuda.empty_cache()
|
| 2137 |
saved = self.trained_dir / f"blk{block}.safetensors"
|
| 2138 |
manager = self._attached(model, block)
|
| 2139 |
-
norm_params =
|
| 2140 |
if saved.exists():
|
| 2141 |
from safetensors.torch import load_file
|
| 2142 |
|
|
@@ -2151,10 +2319,10 @@ class BlockQatTrainer:
|
|
| 2151 |
self._train(model, manager, norm_params, block, h, targets)
|
| 2152 |
except torch.cuda.OutOfMemoryError as e:
|
| 2153 |
raise RuntimeError(
|
| 2154 |
-
f"CUDA out of memory while
|
| 2155 |
-
"
|
| 2156 |
-
"
|
| 2157 |
-
"GPU processes. (PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True "
|
| 2158 |
"also reduces fragmentation.)"
|
| 2159 |
) from e
|
| 2160 |
self._save(model, manager, norm_params, block, saved)
|
|
@@ -2236,234 +2404,257 @@ class BlockQatTrainer:
|
|
| 2236 |
for name, r, rl in rows:
|
| 2237 |
self.log(f" {name:<40s} rmse {r:.3e} rel {100 * rl:.2f}%")
|
| 2238 |
|
| 2239 |
-
|
| 2240 |
-
|
| 2241 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2242 |
for p in model.parameters():
|
| 2243 |
p.requires_grad_(False)
|
| 2244 |
-
|
| 2245 |
-
p.requires_grad_(True)
|
| 2246 |
-
param_groups = [{"params": quant_params, "lr": self.lr, "weight_decay": self.weight_decay}]
|
| 2247 |
-
if norm_params:
|
| 2248 |
-
param_groups.append({
|
| 2249 |
-
"params": norm_params,
|
| 2250 |
-
"lr": self.lr * self.norm_lr_multiplier,
|
| 2251 |
-
"weight_decay": 0.0,
|
| 2252 |
-
})
|
| 2253 |
-
# fused (CUDA) or per-tensor AdamW: the default multi-tensor path needs a
|
| 2254 |
-
# full extra copy of the optimizer state as scratch inside step().
|
| 2255 |
-
opt = None
|
| 2256 |
-
if self.device.type == "cuda":
|
| 2257 |
-
try:
|
| 2258 |
-
opt = torch.optim.AdamW(param_groups, betas=(0.9, 0.95), fused=True)
|
| 2259 |
-
except (RuntimeError, TypeError, ValueError):
|
| 2260 |
-
opt = None
|
| 2261 |
-
if opt is None:
|
| 2262 |
-
opt = torch.optim.AdamW(param_groups, betas=(0.9, 0.95), foreach=False)
|
| 2263 |
-
warmup = int(round(self.warmup_frac * max(1, self.steps)))
|
| 2264 |
-
horizon = max(1, self.steps - warmup)
|
| 2265 |
-
|
| 2266 |
-
def lr_lambda(s: int) -> float:
|
| 2267 |
-
if warmup and s < warmup:
|
| 2268 |
-
return (s + 1) / float(warmup)
|
| 2269 |
-
prog = min(1.0, max(0.0, (s - warmup) / float(horizon)))
|
| 2270 |
-
return 0.05 + 0.95 * 0.5 * (1.0 + math.cos(math.pi * prog))
|
| 2271 |
-
|
| 2272 |
-
scheduler = torch.optim.lr_scheduler.LambdaLR(opt, lr_lambda)
|
| 2273 |
n = h.shape[0]
|
| 2274 |
-
micro = max(1, min(self.micro_batch, n))
|
| 2275 |
-
accum = max(1, self.grad_accum)
|
| 2276 |
-
batch = micro * accum
|
| 2277 |
eval_set = set(self._eval_idx)
|
| 2278 |
train_idx = [i for i in range(n) if i not in eval_set] or list(range(n))
|
| 2279 |
-
|
| 2280 |
-
|
| 2281 |
-
|
| 2282 |
-
|
| 2283 |
-
|
| 2284 |
-
|
| 2285 |
-
|
| 2286 |
-
|
| 2287 |
-
out: list[int] = []
|
| 2288 |
-
while len(out) < k:
|
| 2289 |
-
if cursor >= len(order):
|
| 2290 |
-
rng.shuffle(order)
|
| 2291 |
-
cursor = 0
|
| 2292 |
-
take = order[cursor:cursor + (k - len(out))]
|
| 2293 |
-
cursor += len(take)
|
| 2294 |
-
out.extend(take)
|
| 2295 |
-
return out
|
| 2296 |
-
|
| 2297 |
-
if manager.modules:
|
| 2298 |
-
tq = time.time()
|
| 2299 |
-
manager.refresh() # the same quantization the first forward would do lazily
|
| 2300 |
-
self.log(f"blk.{block}: initial SMQ quantization of {len(manager.modules)} tensors "
|
| 2301 |
-
f"took {time.time() - tq:.0f}s")
|
| 2302 |
-
self._log_weight_rmse(block, manager, "at start (SMQ quantization error)")
|
| 2303 |
-
self._log_eval(block, model, h, targets, "BASELINE, plain SMQ before training")
|
| 2304 |
-
if not self.requant_every and not self.requant_drift:
|
| 2305 |
-
if self.cache_quant_error:
|
| 2306 |
-
self.log(
|
| 2307 |
-
f"blk.{block}: note: no in-loop re-quantization; the forward uses "
|
| 2308 |
-
"the INITIAL quantization error, so weight updates still move it. "
|
| 2309 |
-
"Add requant_every/requant_drift to track the real lattice."
|
| 2310 |
-
)
|
| 2311 |
-
else:
|
| 2312 |
-
self.log(
|
| 2313 |
-
f"blk.{block}: note: requant_every=0 -> the forward keeps using the "
|
| 2314 |
-
"quantization of the INITIAL weights; weight updates only take effect "
|
| 2315 |
-
"at the final re-quantization (w_rmse below will drift upward). "
|
| 2316 |
-
"Use requant_every=N, requant_drift=R, or --cache-quant-error."
|
| 2317 |
-
)
|
| 2318 |
-
if self.cache_quant_error and self.weight_rmse_lambda and manager.modules:
|
| 2319 |
-
self.log(f"blk.{block}: delayed-error cache: weight penalty is applied on "
|
| 2320 |
-
"refresh steps only (where Q(W) is exact)")
|
| 2321 |
-
# Step 0 already has a fresh cache from the initial refresh above.
|
| 2322 |
-
last_refresh = 0 if manager.modules else -10 ** 9
|
| 2323 |
-
if accum > 1:
|
| 2324 |
-
self.log(f"blk.{block}: effective batch = {batch} sequences "
|
| 2325 |
-
f"({micro} x {accum} gradient-accumulation micro-batches)")
|
| 2326 |
-
space = _SpaceStop()
|
| 2327 |
-
if self.adaptive_step:
|
| 2328 |
-
hint = ("press space to stop early and keep the current weights"
|
| 2329 |
-
if space.enabled else
|
| 2330 |
-
"stdin is not a TTY, so space cannot stop this run")
|
| 2331 |
-
self.log(
|
| 2332 |
-
f"blk.{block}: adaptive stepping enabled: continuing with no step limit "
|
| 2333 |
-
f"until block-output rel < {100 * self.adaptive_rel:.1f}% ({hint}); "
|
| 2334 |
-
f"cosine LR horizon is {self.steps} steps"
|
| 2335 |
-
)
|
| 2336 |
-
log_every = (self.log_every if self.log_every > 0 else
|
| 2337 |
-
(max(1, min(self.steps // 10, 10)) if self.adaptive_step
|
| 2338 |
-
else max(1, self.steps // 10)))
|
| 2339 |
-
t0 = time.time()
|
| 2340 |
-
model.train()
|
| 2341 |
try:
|
| 2342 |
-
|
| 2343 |
-
while self.adaptive_step or step < self.steps:
|
| 2344 |
-
# Refresh the fake-quant cache *before* the step so this step's
|
| 2345 |
-
# forward and weight penalty both see an exact Q(W).
|
| 2346 |
-
refreshed_now = (step == 0 and bool(manager.modules))
|
| 2347 |
-
if manager.modules:
|
| 2348 |
-
since = step - last_refresh
|
| 2349 |
-
due, reason = False, ""
|
| 2350 |
-
if self.requant_drift and since >= self.drift_check_every:
|
| 2351 |
-
over, cur, base = manager.drift_exceeded(self.requant_drift)
|
| 2352 |
-
if over:
|
| 2353 |
-
due = True
|
| 2354 |
-
reason = (f"drift {100 * cur:.2f}% vs "
|
| 2355 |
-
f"{100 * base:.2f}% baseline")
|
| 2356 |
-
if self.requant_every and since >= self.requant_every:
|
| 2357 |
-
due = True
|
| 2358 |
-
reason = reason or f"interval {self.requant_every} steps"
|
| 2359 |
-
if due:
|
| 2360 |
-
tq = time.time()
|
| 2361 |
-
manager.refresh()
|
| 2362 |
-
last_refresh = step
|
| 2363 |
-
refreshed_now = True
|
| 2364 |
-
self.log(
|
| 2365 |
-
f"blk.{block}: after step {step}: re-quantized "
|
| 2366 |
-
f"{len(manager.modules)} tensors in {time.time() - tq:.0f}s "
|
| 2367 |
-
f"({reason})")
|
| 2368 |
-
step_idx = next_batch(batch)
|
| 2369 |
-
opt.zero_grad(set_to_none=True)
|
| 2370 |
-
pen_part = None
|
| 2371 |
-
if (self.weight_rmse_lambda and manager.modules
|
| 2372 |
-
and (self.fresh_penalty or not self.cache_quant_error
|
| 2373 |
-
or refreshed_now)):
|
| 2374 |
-
# With delayed-error caching the cached Q(W) is only exact
|
| 2375 |
-
# on refresh steps, so apply the penalty there; between
|
| 2376 |
-
# refreshes it would pull W toward a stale absolute lattice.
|
| 2377 |
-
# --fresh-penalty re-quantizes each step instead (slow).
|
| 2378 |
-
pen = manager.weight_penalty(
|
| 2379 |
-
device=self.device, fresh=self.fresh_penalty).to(dtype=torch.float32)
|
| 2380 |
-
pen_part = self.weight_rmse_lambda * pen
|
| 2381 |
-
# Backprop the (batch-independent) penalty once, so the
|
| 2382 |
-
# micro-batch loop does not reuse its graph.
|
| 2383 |
-
if pen_part.requires_grad:
|
| 2384 |
-
pen_part.backward()
|
| 2385 |
-
else:
|
| 2386 |
-
pen_part = None
|
| 2387 |
-
se_sum = ys_sum = loss_sum = 0.0
|
| 2388 |
-
cnt = 0
|
| 2389 |
-
last_mse = last_cos = 0.0
|
| 2390 |
-
for g in range(accum):
|
| 2391 |
-
sub = step_idx[g * micro:(g + 1) * micro]
|
| 2392 |
-
x = h[sub].to(device=self.device, dtype=torch.float32)
|
| 2393 |
-
y = targets[sub].to(device=self.device, dtype=torch.float32)
|
| 2394 |
-
ctx = torch.autocast(device_type=self.device.type, dtype=self.autocast_dtype)
|
| 2395 |
-
with ctx:
|
| 2396 |
-
pred = _forward_layer_train(model, x)
|
| 2397 |
-
pred_f = pred.float()
|
| 2398 |
-
mse = F.mse_loss(pred_f, y)
|
| 2399 |
-
loss = mse
|
| 2400 |
-
cos_part = None
|
| 2401 |
-
if self.cosine_lambda:
|
| 2402 |
-
cos_loss = (1.0 - F.cosine_similarity(pred_f, y, dim=-1)).mean()
|
| 2403 |
-
cos_part = self.cosine_lambda * cos_loss
|
| 2404 |
-
loss = loss + cos_part
|
| 2405 |
-
# Scale by the number of micro-batches so the accumulated
|
| 2406 |
-
# gradient is the mean over `batch`, not a sum.
|
| 2407 |
-
(loss / accum).backward()
|
| 2408 |
-
with torch.no_grad():
|
| 2409 |
-
se_sum += float((pred_f.detach() - y).pow(2).sum())
|
| 2410 |
-
ys_sum += float(y.pow(2).sum())
|
| 2411 |
-
cnt += y.numel()
|
| 2412 |
-
loss_sum += float(loss.detach())
|
| 2413 |
-
last_mse = float(mse.detach())
|
| 2414 |
-
last_cos = float(cos_part.detach()) if cos_part is not None else 0.0
|
| 2415 |
-
torch.nn.utils.clip_grad_norm_(all_params, 1.0)
|
| 2416 |
-
opt.step()
|
| 2417 |
-
scheduler.step()
|
| 2418 |
-
opt.zero_grad(set_to_none=True)
|
| 2419 |
-
out_rmse = (se_sum / max(cnt, 1)) ** 0.5
|
| 2420 |
-
y_rms = (ys_sum / max(cnt, 1)) ** 0.5
|
| 2421 |
-
out_rel = out_rmse / max(y_rms, 1e-30)
|
| 2422 |
-
at_end = not self.adaptive_step and step + 1 == self.steps
|
| 2423 |
-
if (step + 1) % log_every == 0 or at_end:
|
| 2424 |
-
with torch.no_grad():
|
| 2425 |
-
w_rmse, w_rel, _rows = manager.weight_rmse()
|
| 2426 |
-
terms = f"mse {last_mse:.2e}"
|
| 2427 |
-
if self.cosine_lambda:
|
| 2428 |
-
terms += f" + cos {last_cos:.2e}"
|
| 2429 |
-
if pen_part is not None:
|
| 2430 |
-
terms += f" + wpen {float(pen_part.detach()):.2e}"
|
| 2431 |
-
logged_loss = loss_sum / accum + (
|
| 2432 |
-
float(pen_part.detach()) if pen_part is not None else 0.0)
|
| 2433 |
-
total = "" if self.adaptive_step else f"/{self.steps}"
|
| 2434 |
-
self.log(
|
| 2435 |
-
f"blk.{block}: step {step + 1}{total} loss={logged_loss:.6e} "
|
| 2436 |
-
f"[{terms}] out_rmse={out_rmse:.3e} (rel {100 * out_rel:.1f}%) "
|
| 2437 |
-
f"w_rmse={w_rmse:.3e} (rel {100 * w_rel:.2f}%) "
|
| 2438 |
-
f"lr={scheduler.get_last_lr()[0]:.2e} ({(time.time() - t0) / (step + 1):.2f}s/step)"
|
| 2439 |
-
)
|
| 2440 |
-
if space.pressed():
|
| 2441 |
-
self.log(f"blk.{block}: space pressed at step {step + 1}; "
|
| 2442 |
-
"keeping the current weights")
|
| 2443 |
-
break
|
| 2444 |
-
if self.adaptive_step and out_rel < self.adaptive_rel:
|
| 2445 |
-
# Confirm the minibatch estimate on the held-out set before
|
| 2446 |
-
# ending the block early.
|
| 2447 |
-
was_training = model.training
|
| 2448 |
-
model.eval()
|
| 2449 |
-
try:
|
| 2450 |
-
_rmse, rel, _cos = self._eval_block(model, h, targets)
|
| 2451 |
-
finally:
|
| 2452 |
-
model.train(was_training)
|
| 2453 |
-
if rel < self.adaptive_rel:
|
| 2454 |
-
self.log(
|
| 2455 |
-
f"blk.{block}: adaptive stop at step {step + 1}: "
|
| 2456 |
-
f"block-output rel {100 * rel:.2f}% < "
|
| 2457 |
-
f"{100 * self.adaptive_rel:.2f}%"
|
| 2458 |
-
)
|
| 2459 |
-
break
|
| 2460 |
-
step += 1
|
| 2461 |
finally:
|
| 2462 |
-
|
| 2463 |
-
del opt, scheduler # free Adam state (2 x params) before propagation
|
| 2464 |
gc.collect()
|
| 2465 |
if torch.cuda.is_available():
|
| 2466 |
torch.cuda.empty_cache()
|
|
|
|
|
|
|
| 2467 |
|
| 2468 |
def _load_saved(self, model, block: int, sd: dict) -> int:
|
| 2469 |
"""Copy a saved checkpoint's tensors into the model originals and norms."""
|
|
@@ -2871,8 +3062,19 @@ def train(
|
|
| 2871 |
offload_threshold: int = 64,
|
| 2872 |
quant_workers: int | None = None,
|
| 2873 |
verbose: bool = False,
|
|
|
|
|
|
|
|
|
|
| 2874 |
) -> int:
|
| 2875 |
-
"""Block-wise QAT against SMQ's real Q2_K quantizer.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2876 |
|
| 2877 |
``blocks`` is (lo, hi) with hi exclusive, exactly like the reference.
|
| 2878 |
``adaptive_step`` continues each block with no step limit until the
|
|
@@ -2932,6 +3134,8 @@ def train(
|
|
| 2932 |
log(f"QAT: tensor-type {name}={tt} ignored (SMQ emits Q2_K only)")
|
| 2933 |
log(f"QAT: {gguf_path}")
|
| 2934 |
log(f"QAT: plan = {n_quant} Q2_K tensors")
|
|
|
|
|
|
|
| 2935 |
log(f"QAT: blocks {lo}..{hi - 1} of {n_real}")
|
| 2936 |
if n_nextn:
|
| 2937 |
log(
|
|
@@ -2976,6 +3180,9 @@ def train(
|
|
| 2976 |
seed=seed,
|
| 2977 |
verbose=verbose,
|
| 2978 |
log=log,
|
|
|
|
|
|
|
|
|
|
| 2979 |
)
|
| 2980 |
h: _ActivationBuffer | None = None
|
| 2981 |
for b in range(lo, hi):
|
|
|
|
| 203 |
return None
|
| 204 |
|
| 205 |
|
| 206 |
+
def quantize_pack(W: np.ndarray, importance=None) -> np.ndarray:
|
| 207 |
+
"""Run the real SMQ quantizer on *W* and return the packed Q2_K payload.
|
|
|
|
|
|
|
|
|
|
| 208 |
|
| 209 |
W: (rows, cols) float32 with cols % 256 == 0 (blocks run along the input
|
| 210 |
axis, exactly as the converter packs them). ``importance`` is whatever
|
| 211 |
``factorize_q2k`` accepts: None, a per-block (n, 256) array, or a
|
| 212 |
+
FullWeights / ChannelWeights object. Returns the (n_blocks, 84) uint8
|
| 213 |
+
payload, blocks row-major over (rows, cols / 256).
|
| 214 |
"""
|
| 215 |
W = np.ascontiguousarray(W, dtype=np.float32)
|
| 216 |
rows, cols = W.shape
|
|
|
|
| 224 |
rtn_baseline=True,
|
| 225 |
weights=importance,
|
| 226 |
)
|
| 227 |
+
return packed
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def decode_packed(packed: np.ndarray, rows: int, cols: int) -> np.ndarray:
|
| 231 |
+
"""Bit-exact decode of a packed Q2_K payload to (rows, cols) float32."""
|
| 232 |
rec = smqc.unpack_q2k_blocks_for_test(packed) # (n_blocks, 256), bit-exact
|
| 233 |
+
return np.ascontiguousarray(np.asarray(rec).reshape(rows, cols), dtype=np.float32)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def quantize_dequantize(
|
| 237 |
+
W: np.ndarray,
|
| 238 |
+
importance=None,
|
| 239 |
+
) -> np.ndarray:
|
| 240 |
+
"""Run the real SMQ quantizer on *W* and return the dequantized weights."""
|
| 241 |
+
W = np.ascontiguousarray(W, dtype=np.float32)
|
| 242 |
+
rows, cols = W.shape
|
| 243 |
+
return decode_packed(quantize_pack(W, importance), rows, cols)
|
| 244 |
|
| 245 |
|
| 246 |
def quantize_dequantize_torch(
|
|
|
|
| 248 |
importance=None,
|
| 249 |
device=None,
|
| 250 |
round_dtype: "torch.dtype | None" = None,
|
| 251 |
+
return_packed: bool = False,
|
| 252 |
+
):
|
| 253 |
"""Fake-quant *W* with the real SMQ quantizer (numpy engine, CPU).
|
| 254 |
|
| 255 |
The full-precision weight crosses to the CPU, SMQ quantizes + decodes it
|
|
|
|
| 258 |
no torch kernels, so this is the faithful round-trip.
|
| 259 |
|
| 260 |
``round_dtype`` first rounds *W* onto the storage lattice the export uses
|
| 261 |
+
(``torch.float16`` for trained 2-D projections), so the quantizer sees the
|
| 262 |
+
same values the converter will actually quantize. With ``return_packed``
|
| 263 |
+
the packed Q2_K payload is returned too: ``(decoded, packed)``.
|
| 264 |
"""
|
| 265 |
if round_dtype is not None:
|
| 266 |
# Round on the GPU, transfer the *half-size* payload, and widen on the
|
|
|
|
| 268 |
arr = W.detach().to(round_dtype).cpu().numpy().astype(np.float32, copy=False)
|
| 269 |
else:
|
| 270 |
arr = W.detach().float().cpu().numpy()
|
| 271 |
+
arr = np.ascontiguousarray(arr, dtype=np.float32)
|
| 272 |
+
packed = quantize_pack(arr, importance)
|
| 273 |
+
rec = decode_packed(packed, *arr.shape)
|
| 274 |
+
out = torch.from_numpy(rec).to(
|
| 275 |
device=W.device if device is None else device, dtype=W.dtype)
|
| 276 |
+
return (out, packed) if return_packed else out
|
| 277 |
|
| 278 |
|
| 279 |
class QatWeight(nn.Module):
|
|
|
|
| 282 |
def __init__(self, importance=None, offload: bool = False,
|
| 283 |
round_dtype: "torch.dtype | None" = None,
|
| 284 |
cache_device: bool | None = None,
|
| 285 |
+
cache_error: bool = False,
|
| 286 |
+
keep_packed: bool = False):
|
| 287 |
super().__init__()
|
| 288 |
self.importance = importance
|
| 289 |
self.offload = offload # keep the decoded cache in (pinned) CPU RAM
|
|
|
|
| 293 |
# decoded weights are not being offloaded.
|
| 294 |
self.cache_device = (not offload) if cache_device is None else bool(cache_device)
|
| 295 |
self.q = None
|
| 296 |
+
self.keep_packed = keep_packed
|
| 297 |
+
self.packed = None # packed Q2_K payload of the last refresh (algebraic QAT)
|
| 298 |
self.err = None # Q(W_ref) - W_ref, forward = W + err
|
| 299 |
self._dev_q = None
|
| 300 |
self._dev_err = None
|
|
|
|
| 345 |
def refresh(self, W: "torch.Tensor") -> None:
|
| 346 |
"""Re-quantize *W* with the real SMQ engine and cache the decoded copy."""
|
| 347 |
if self.offload:
|
| 348 |
+
q, packed = quantize_dequantize_torch(
|
| 349 |
+
W, self.importance, device="cpu", round_dtype=self.round_dtype,
|
| 350 |
+
return_packed=True)
|
| 351 |
+
self.packed = packed if self.keep_packed else None
|
| 352 |
if self.cache_error:
|
| 353 |
# err is relative to the fp32 W on its device, computed there
|
| 354 |
# once per refresh (not once per forward), then pinned for H2D.
|
|
|
|
| 364 |
pass
|
| 365 |
self.q = q
|
| 366 |
else:
|
| 367 |
+
self.q, packed = quantize_dequantize_torch(
|
| 368 |
+
W, self.importance, round_dtype=self.round_dtype, return_packed=True)
|
| 369 |
+
self.packed = packed if self.keep_packed else None
|
| 370 |
self.err = (self.q - W) if self.cache_error else None
|
| 371 |
self._dev_q = None
|
| 372 |
self._dev_err = None
|
|
|
|
| 385 |
round_dtype: "torch.dtype | None" = None,
|
| 386 |
max_workers: int | None = None,
|
| 387 |
cache_error: bool = False,
|
| 388 |
+
track_drift: bool = False,
|
| 389 |
+
keep_packed: bool = False):
|
| 390 |
+
self.keep_packed = keep_packed
|
| 391 |
self.offload_q = offload_q
|
| 392 |
self.round_dtype = round_dtype
|
| 393 |
# SMQ is numpy + per-tensor; independent tensors quantize in parallel.
|
|
|
|
| 408 |
self.names.append(name or f"module{len(self.modules) - 1}")
|
| 409 |
return True
|
| 410 |
qw = QatWeight(importance, self.offload_q, self.round_dtype,
|
| 411 |
+
cache_error=self.cache_error,
|
| 412 |
+
keep_packed=self.keep_packed)
|
| 413 |
qw._defer = True
|
| 414 |
try:
|
| 415 |
P.register_parametrization(module, "weight", qw)
|
|
|
|
| 1884 |
return self.inner.chunk(self.off + c0, self.off + c1, qk)
|
| 1885 |
|
| 1886 |
|
| 1887 |
+
# ---------------------------------------------------------------------------
|
| 1888 |
+
# Algebraic (closed-form) QAT
|
| 1889 |
+
#
|
| 1890 |
+
# Q2_K decodes each 16-weight sub-block as w = s*q - o with 2-bit codes q.
|
| 1891 |
+
# For fixed codes a linear layer's output is *linear* in (s, o), so
|
| 1892 |
+
# min_{s,o} || X (s*q - o)^T - Y ||^2
|
| 1893 |
+
# is a least-squares problem, solved exactly with the normal equations. The
|
| 1894 |
+
# normal equations only need the Gram matrices C = X^T X and G = X^T Y (and
|
| 1895 |
+
# Y^T Y), which are accumulated by streaming over tokens -- X itself is never
|
| 1896 |
+
# stored and the solve cost does not depend on the token count:
|
| 1897 |
+
# A_r = M_r^T C M_r, b_r = M_r^T G[:, r]
|
| 1898 |
+
# where M_r maps the 2J unknowns (s_j, o_j) of row r to the d weights.
|
| 1899 |
+
# Scales are then snapped to the Q2_K lattice (4-bit scale/min nibbles under
|
| 1900 |
+
# fp16 super-scales) and, optionally, the codes are re-derived and the solve is
|
| 1901 |
+
# repeated. Every candidate is guarded per output row: a row only takes the
|
| 1902 |
+
# new weights if its output error improves on both the fitting tokens and the
|
| 1903 |
+
# held-out tokens.
|
| 1904 |
+
# ---------------------------------------------------------------------------
|
| 1905 |
+
|
| 1906 |
+
SUB = 16 # weights per Q2_K sub-block
|
| 1907 |
+
NSUB = 16 # sub-blocks per super-block (256 weights)
|
| 1908 |
+
|
| 1909 |
+
|
| 1910 |
+
def _q2k_unpack(packed: np.ndarray, m: int, d: int):
|
| 1911 |
+
"""Packed payload -> codes (m, J, 16) uint8, s (m, J) f32, o (m, J) f32."""
|
| 1912 |
+
p = np.asarray(packed, dtype=np.uint8)
|
| 1913 |
+
nb = p.shape[0]
|
| 1914 |
+
if nb != m * (d // QK):
|
| 1915 |
+
raise ValueError(f"payload has {nb} blocks, expected {m * (d // QK)}")
|
| 1916 |
+
scales = p[:, :16]
|
| 1917 |
+
qs = p[:, 16:80]
|
| 1918 |
+
d_super = p[:, 80:82].copy().reshape(-1).view("<f2").astype(np.float32)
|
| 1919 |
+
dmin_super = p[:, 82:84].copy().reshape(-1).view("<f2").astype(np.float32)
|
| 1920 |
+
ls = (scales & 0x0F).astype(np.float32)
|
| 1921 |
+
lm = (scales >> 4).astype(np.float32)
|
| 1922 |
+
shifts = np.array([0, 2, 4, 6], dtype=np.uint8).reshape(1, 1, 4, 1)
|
| 1923 |
+
codes = ((qs.reshape(nb, 2, 1, 32) >> shifts) & np.uint8(3)).reshape(nb, NSUB, SUB)
|
| 1924 |
+
s = d_super[:, None] * ls
|
| 1925 |
+
o = dmin_super[:, None] * lm
|
| 1926 |
+
J = d // SUB
|
| 1927 |
+
return (np.ascontiguousarray(codes, dtype=np.uint8).reshape(m, J, SUB),
|
| 1928 |
+
np.ascontiguousarray(s).reshape(m, J),
|
| 1929 |
+
np.ascontiguousarray(o).reshape(m, J))
|
| 1930 |
+
|
| 1931 |
+
|
| 1932 |
+
def _q2k_decode(q: "torch.Tensor", s: "torch.Tensor", o: "torch.Tensor") -> "torch.Tensor":
|
| 1933 |
+
m, J, _ = q.shape
|
| 1934 |
+
return (s[..., None] * q.to(s.dtype) - o[..., None]).reshape(m, J * SUB)
|
| 1935 |
+
|
| 1936 |
+
|
| 1937 |
+
def _snap_scales(s: "torch.Tensor", o: "torch.Tensor"):
|
| 1938 |
+
"""Snap per-sub-block (s, o) to the Q2_K lattice (codes are untouched)."""
|
| 1939 |
+
m, J = s.shape
|
| 1940 |
+
if J % NSUB:
|
| 1941 |
+
raise ValueError("J must be a multiple of 16")
|
| 1942 |
+
S = s.reshape(m, J // NSUB, NSUB)
|
| 1943 |
+
O = o.reshape(m, J // NSUB, NSUB)
|
| 1944 |
+
d = (S.amax(-1) / 15.0).to(torch.float16).to(torch.float32)
|
| 1945 |
+
dmin = (O.amax(-1) / 15.0).to(torch.float16).to(torch.float32)
|
| 1946 |
+
ls = torch.where(d[..., None] > 0,
|
| 1947 |
+
torch.round(S / d[..., None].clamp_min(1e-30)),
|
| 1948 |
+
torch.zeros_like(S)).clamp(0, 15)
|
| 1949 |
+
lm = torch.where(dmin[..., None] > 0,
|
| 1950 |
+
torch.round(O / dmin[..., None].clamp_min(1e-30)),
|
| 1951 |
+
torch.zeros_like(O)).clamp(0, 15)
|
| 1952 |
+
return (d[..., None] * ls).reshape(m, J), (dmin[..., None] * lm).reshape(m, J)
|
| 1953 |
+
|
| 1954 |
+
|
| 1955 |
+
def _rederive_codes(s: "torch.Tensor", o: "torch.Tensor", W_src: "torch.Tensor") -> "torch.Tensor":
|
| 1956 |
+
"""Nearest 2-bit codes of W_src for the given (snapped) scales, uint8."""
|
| 1957 |
+
m, J = s.shape
|
| 1958 |
+
Wg = W_src.reshape(m, J, SUB)
|
| 1959 |
+
safe = torch.where(s > 0, s, torch.ones_like(s))
|
| 1960 |
+
q = torch.round((Wg + o[..., None]) / safe[..., None]).clamp(0, 3)
|
| 1961 |
+
q = torch.where(s[..., None] > 0, q, torch.zeros_like(q))
|
| 1962 |
+
return q.to(torch.uint8)
|
| 1963 |
+
|
| 1964 |
+
|
| 1965 |
+
def _row_err_gram(W, C, G, yy, chunk: int = 4096):
|
| 1966 |
+
"""Per-output-row sum over tokens of (X w_r - y_r)^2, from Gram matrices."""
|
| 1967 |
+
m = W.shape[0]
|
| 1968 |
+
out = torch.empty(m, device=W.device, dtype=W.dtype)
|
| 1969 |
+
for r0 in range(0, m, chunk):
|
| 1970 |
+
r1 = min(m, r0 + chunk)
|
| 1971 |
+
Wc = W[r0:r1]
|
| 1972 |
+
out[r0:r1] = (((Wc @ C) * Wc).sum(1)
|
| 1973 |
+
- 2.0 * (Wc * G[:, r0:r1].t()).sum(1) + yy[r0:r1])
|
| 1974 |
+
return out
|
| 1975 |
+
|
| 1976 |
|
| 1977 |
+
def _row_err_val(W, Xv, Yv, chunk: int = 4096):
|
| 1978 |
+
"""Per-output-row sum of squared error on explicit held-out tokens."""
|
| 1979 |
+
m = W.shape[0]
|
| 1980 |
+
out = torch.empty(m, device=W.device, dtype=W.dtype)
|
| 1981 |
+
for r0 in range(0, m, chunk):
|
| 1982 |
+
r1 = min(m, r0 + chunk)
|
| 1983 |
+
out[r0:r1] = (Xv @ W[r0:r1].t() - Yv[:, r0:r1]).pow(2).sum(0)
|
| 1984 |
+
return out
|
| 1985 |
+
|
| 1986 |
+
|
| 1987 |
+
@torch.no_grad()
|
| 1988 |
+
def _ls_fit_gram(C, G, q, s0, o0, ridge: float, row_chunk: int = 0,
|
| 1989 |
+
budget: int = 3 * 2 ** 29):
|
| 1990 |
+
"""Closed-form (s, o) for fixed codes from the Gram matrices.
|
| 1991 |
+
|
| 1992 |
+
C: (d, d) = X^T X, G: (d, m) = X^T Y, q: (m, J, 16) codes (any int dtype),
|
| 1993 |
+
s0/o0: (m, J) current scales, used as the *prior* of a proximal ridge
|
| 1994 |
+
(directions the data does not determine stay at their current value, so
|
| 1995 |
+
dead input channels never zero a weight). The system is Jacobi-scaled to a
|
| 1996 |
+
unit diagonal first; ``ridge`` is relative to that unit diagonal.
|
| 1997 |
+
Returns (s, o) clamped to >= 0.
|
| 1998 |
"""
|
| 1999 |
+
d = C.shape[0]
|
| 2000 |
+
m, J, sub = q.shape
|
| 2001 |
+
if sub != SUB or J * SUB != d:
|
| 2002 |
+
raise ValueError("q shape does not match the Gram matrix")
|
| 2003 |
+
dev, dt = C.device, C.dtype
|
| 2004 |
+
C4m = C.view(J, SUB, d) # [j, a, (k, b)]
|
| 2005 |
+
Cs = C.view(J, SUB, J, SUB).sum(-1) # [j, a, k] = sum_b C[(j,a),(k,b)]
|
| 2006 |
+
VtV = Cs.sum(1) # [j, k]
|
| 2007 |
+
if row_chunk <= 0:
|
| 2008 |
+
row_chunk = int(max(1, min(64, budget // (128 * J * J))))
|
| 2009 |
+
eye = torch.eye(2 * J, device=dev, dtype=dt)
|
| 2010 |
+
s_out = torch.empty(m, J, device=dev, dtype=dt)
|
| 2011 |
+
o_out = torch.empty(m, J, device=dev, dtype=dt)
|
| 2012 |
+
for r0 in range(0, m, row_chunk):
|
| 2013 |
+
r1 = min(m, r0 + row_chunk)
|
| 2014 |
+
R = r1 - r0
|
| 2015 |
+
qc = q[r0:r1].to(dt) # (R, J, 16)
|
| 2016 |
+
Qj = qc.permute(1, 0, 2).contiguous() # (J, R, 16)
|
| 2017 |
+
T = torch.bmm(Qj, C4m).view(J, R, J, SUB) # [j, r, k, b]
|
| 2018 |
+
T.mul_(qc.unsqueeze(0)) # * q[r, k, b]
|
| 2019 |
+
UtU = T.sum(-1).permute(1, 0, 2) # (R, J, J)
|
| 2020 |
+
del T
|
| 2021 |
+
UtV = torch.bmm(Qj, Cs).permute(1, 0, 2) # (R, J, J)
|
| 2022 |
+
A = torch.empty(R, 2 * J, 2 * J, device=dev, dtype=dt)
|
| 2023 |
+
A[:, :J, :J] = UtU
|
| 2024 |
+
A[:, :J, J:] = -UtV
|
| 2025 |
+
A[:, J:, :J] = -UtV.transpose(1, 2)
|
| 2026 |
+
A[:, J:, J:] = VtV
|
| 2027 |
+
del UtU, UtV
|
| 2028 |
+
A = 0.5 * (A + A.transpose(1, 2))
|
| 2029 |
+
Gr = G[:, r0:r1].t().reshape(R, J, SUB)
|
| 2030 |
+
b = torch.cat([(qc * Gr).sum(-1), -Gr.sum(-1)], dim=-1) # (R, 2J)
|
| 2031 |
+
th0 = torch.cat([s0[r0:r1], o0[r0:r1]], dim=-1).to(dt)
|
| 2032 |
+
diag = A.diagonal(dim1=-2, dim2=-1)
|
| 2033 |
+
dg = diag.clamp_min(diag.amax(-1, keepdim=True) * 1e-12 + 1e-30).sqrt()
|
| 2034 |
+
An = A / (dg[:, :, None] * dg[:, None, :])
|
| 2035 |
+
del A
|
| 2036 |
+
lam = torch.full((R,), float(ridge), device=dev, dtype=dt)
|
| 2037 |
+
ok = torch.zeros(R, dtype=torch.bool, device=dev)
|
| 2038 |
+
L = None
|
| 2039 |
+
for _ in range(4):
|
| 2040 |
+
M = An + lam[:, None, None] * eye
|
| 2041 |
+
L, info = torch.linalg.cholesky_ex(M)
|
| 2042 |
+
ok = info == 0
|
| 2043 |
+
if bool(ok.all()):
|
| 2044 |
+
break
|
| 2045 |
+
lam = torch.where(ok, lam, lam * 100.0)
|
| 2046 |
+
th0s = th0 * dg
|
| 2047 |
+
rhs = b / dg + lam[:, None] * th0s
|
| 2048 |
+
sol = torch.cholesky_solve(rhs.unsqueeze(-1), L).squeeze(-1)
|
| 2049 |
+
sol = torch.where(ok[:, None], sol, th0s) # fallback: keep prior
|
| 2050 |
+
th = sol / dg
|
| 2051 |
+
s_out[r0:r1] = th[:, :J].clamp_min(0)
|
| 2052 |
+
o_out[r0:r1] = th[:, J:].clamp_min(0)
|
| 2053 |
+
return s_out, o_out
|
| 2054 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2055 |
|
| 2056 |
+
class _StopForward(Exception):
|
| 2057 |
+
"""Raised from a pre-hook to abort a block forward once the input is captured."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2058 |
|
|
|
|
|
|
|
|
|
|
| 2059 |
|
| 2060 |
+
def _capture_input(model, module, x: "torch.Tensor") -> "torch.Tensor":
|
| 2061 |
+
"""Input tensor of *module* for the block forward on *x* (stops early)."""
|
| 2062 |
+
box: dict = {}
|
| 2063 |
+
|
| 2064 |
+
def hook(_m, args):
|
| 2065 |
+
box["x"] = args[0].detach()
|
| 2066 |
+
raise _StopForward
|
| 2067 |
+
|
| 2068 |
+
handle = module.register_forward_pre_hook(hook)
|
| 2069 |
+
try:
|
| 2070 |
+
model(inputs_embeds=x, use_cache=False)
|
| 2071 |
+
except _StopForward:
|
| 2072 |
+
pass
|
| 2073 |
+
finally:
|
| 2074 |
+
handle.remove()
|
| 2075 |
+
if "x" not in box:
|
| 2076 |
+
raise RuntimeError("algebraic QAT: target projection was never called in the block forward")
|
| 2077 |
+
return box["x"]
|
| 2078 |
+
|
| 2079 |
+
|
| 2080 |
+
def _set_weights(params, tensors) -> None:
|
| 2081 |
+
for p, t in zip(params, tensors):
|
| 2082 |
+
p.data = t
|
| 2083 |
|
| 2084 |
|
| 2085 |
class BlockQatTrainer:
|
|
|
|
| 2119 |
seed: int = 0,
|
| 2120 |
verbose: bool = False,
|
| 2121 |
log=print,
|
| 2122 |
+
ls_iters: int = 2,
|
| 2123 |
+
ls_ridge: float = 1.0e-3,
|
| 2124 |
+
ls_row_chunk: int = 0,
|
| 2125 |
):
|
| 2126 |
self.reader = reader
|
| 2127 |
self.imat = imat
|
|
|
|
| 2142 |
self.warmup_frac = max(0.0, float(warmup_frac))
|
| 2143 |
self.round_dtype = torch.float16 if (fp16_round and torch is not None) else None
|
| 2144 |
self.fresh_penalty = fresh_penalty
|
| 2145 |
+
self.cache_quant_error = False # unused: the algebraic fit has no delayed-error cache
|
| 2146 |
+
self.ls_iters = max(1, int(ls_iters))
|
| 2147 |
+
self.ls_ridge = float(ls_ridge)
|
| 2148 |
+
self.ls_row_chunk = max(0, int(ls_row_chunk))
|
| 2149 |
self.requant_drift = max(0.0, float(requant_drift))
|
| 2150 |
self.drift_check_every = max(1, int(drift_check_every))
|
| 2151 |
# 0 = automatic cadence (steps // 10, capped at 10 for adaptive runs).
|
|
|
|
| 2200 |
def _attached(self, model, block: int):
|
| 2201 |
manager = QatManager(
|
| 2202 |
offload_q=self._offload_q_now, round_dtype=self.round_dtype,
|
| 2203 |
+
max_workers=self.quant_workers, cache_error=False,
|
| 2204 |
+
track_drift=False, keep_packed=True)
|
| 2205 |
layer = _get_decoder_layers(model)[0]
|
| 2206 |
for gguf_name, hf_name in self._trainable(block):
|
| 2207 |
try:
|
|
|
|
| 2241 |
return n
|
| 2242 |
|
| 2243 |
def _plan_memory(self, block: int) -> bool:
|
| 2244 |
+
"""Log the memory estimate for the algebraic fit (no optimizer state).
|
| 2245 |
|
| 2246 |
+
Per trainable parameter (fp32): student weight 4 + decoded cache 4 +
|
| 2247 |
+
codes 1 + decode/snap temporaries ~4 = ~13 B. On top of that each input
|
| 2248 |
+
group holds a d x d Gram matrix and a d x m cross-Gram per projection.
|
| 2249 |
+
The decoded cache always stays on the training device.
|
| 2250 |
"""
|
| 2251 |
if self.device.type != "cuda":
|
| 2252 |
return False
|
| 2253 |
gib = 2 ** 30
|
| 2254 |
n = self._est_trainable_params(block)
|
| 2255 |
free, _total = torch.cuda.mem_get_info(self.device)
|
| 2256 |
+
need = 13 * n
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2257 |
self.log(
|
| 2258 |
+
f"blk.{block}: {n / 1e6:.0f}M trainable params -> ~{need / gib:.1f} GiB "
|
| 2259 |
+
f"(+ Gram matrices + activations) vs {free / gib:.1f} GiB free"
|
|
|
|
| 2260 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2261 |
if need + gib > free:
|
| 2262 |
self.log(
|
| 2263 |
f"blk.{block}: WARNING: likely to run out of VRAM; consider a smaller "
|
| 2264 |
+
"micro_batch or seq_len, train_types=<subset>, or closing other GPU processes"
|
| 2265 |
)
|
| 2266 |
+
return False
|
| 2267 |
|
| 2268 |
def train_block(self, block: int, h: "_ActivationBuffer", hf_dir: Path) -> "_ActivationBuffer":
|
| 2269 |
"""Train one block; returns the activations to feed the next block."""
|
|
|
|
| 2304 |
torch.cuda.empty_cache()
|
| 2305 |
saved = self.trained_dir / f"blk{block}.safetensors"
|
| 2306 |
manager = self._attached(model, block)
|
| 2307 |
+
norm_params: list = [] # norms are not co-adapted by the algebraic fit
|
| 2308 |
if saved.exists():
|
| 2309 |
from safetensors.torch import load_file
|
| 2310 |
|
|
|
|
| 2319 |
self._train(model, manager, norm_params, block, h, targets)
|
| 2320 |
except torch.cuda.OutOfMemoryError as e:
|
| 2321 |
raise RuntimeError(
|
| 2322 |
+
f"CUDA out of memory while fitting blk.{block}. Try: "
|
| 2323 |
+
"a smaller micro_batch or seq_len, train_types=<subset of tensor "
|
| 2324 |
+
"types> (the d x d Gram of ffn_down is the largest object), or free "
|
| 2325 |
+
"other GPU processes. (PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True "
|
| 2326 |
"also reduces fragmentation.)"
|
| 2327 |
) from e
|
| 2328 |
self._save(model, manager, norm_params, block, saved)
|
|
|
|
| 2404 |
for name, r, rl in rows:
|
| 2405 |
self.log(f" {name:<40s} rmse {r:.3e} rel {100 * rl:.2f}%")
|
| 2406 |
|
| 2407 |
+
# -- algebraic fit ------------------------------------------------------
|
| 2408 |
+
|
| 2409 |
+
def _discover_groups(self, model, manager, h):
|
| 2410 |
+
"""Order the attached projections by execution and group shared inputs.
|
| 2411 |
+
|
| 2412 |
+
Projections that consume the very same input tensor (q/k/v, gate/up, ...)
|
| 2413 |
+
share one Gram matrix and are solved together; a later group sees the
|
| 2414 |
+
already-quantized outputs of the earlier ones. Returns
|
| 2415 |
+
(groups, unused): lists of indices into ``manager.modules``.
|
| 2416 |
+
"""
|
| 2417 |
+
mods = [m for m, _ in manager.modules]
|
| 2418 |
+
seen: list = []
|
| 2419 |
+
keep: list = []
|
| 2420 |
+
handles = []
|
| 2421 |
+
|
| 2422 |
+
def mk(i):
|
| 2423 |
+
def hook(_m, args):
|
| 2424 |
+
x = args[0]
|
| 2425 |
+
keep.append(x) # keep alive so data_ptr() stays unique
|
| 2426 |
+
seen.append((i, (x.data_ptr(), tuple(x.shape), tuple(x.stride()), x.dtype)))
|
| 2427 |
+
return hook
|
| 2428 |
+
|
| 2429 |
+
for i, m in enumerate(mods):
|
| 2430 |
+
handles.append(m.register_forward_pre_hook(mk(i)))
|
| 2431 |
+
try:
|
| 2432 |
+
idx = list(self._eval_idx[:1]) or [0]
|
| 2433 |
+
x = h[idx].to(device=self.device, dtype=torch.float32)
|
| 2434 |
+
with torch.no_grad():
|
| 2435 |
+
model(inputs_embeds=x, use_cache=False)
|
| 2436 |
+
finally:
|
| 2437 |
+
for hd in handles:
|
| 2438 |
+
hd.remove()
|
| 2439 |
+
groups: list[list[int]] = []
|
| 2440 |
+
by_key: dict = {}
|
| 2441 |
+
placed: set[int] = set()
|
| 2442 |
+
for i, key in seen:
|
| 2443 |
+
if i in placed:
|
| 2444 |
+
continue
|
| 2445 |
+
placed.add(i)
|
| 2446 |
+
g = by_key.get(key)
|
| 2447 |
+
if g is None:
|
| 2448 |
+
g = []
|
| 2449 |
+
by_key[key] = g
|
| 2450 |
+
groups.append(g)
|
| 2451 |
+
g.append(i)
|
| 2452 |
+
unused = [i for i in range(len(mods)) if i not in placed]
|
| 2453 |
+
return groups, unused
|
| 2454 |
+
|
| 2455 |
+
@torch.no_grad()
|
| 2456 |
+
def _collect_group_stats(self, model, mods, params, W_fp, W_stu, grp, h,
|
| 2457 |
+
train_idx, eval_idx, solved_any: bool):
|
| 2458 |
+
"""Stream Gram statistics for one input group.
|
| 2459 |
+
|
| 2460 |
+
Student input X_q comes from the block with the earlier groups already
|
| 2461 |
+
quantized; the target Y = X_fp W_fp^T comes from the pure fp block.
|
| 2462 |
+
Returns C (d,d), G list (d,m_k), yy list (m_k), and held-out Xv / Yv list.
|
| 2463 |
+
"""
|
| 2464 |
+
dev = self.device
|
| 2465 |
+
first = mods[grp[0]]
|
| 2466 |
+
d = W_fp[grp[0]].shape[1]
|
| 2467 |
+
micro = max(1, min(self.micro_batch, max(len(train_idx), 1)))
|
| 2468 |
+
C = torch.zeros(d, d, device=dev, dtype=torch.float32)
|
| 2469 |
+
G = [torch.zeros(d, W_fp[k].shape[0], device=dev, dtype=torch.float32) for k in grp]
|
| 2470 |
+
yy = [torch.zeros(W_fp[k].shape[0], device=dev, dtype=torch.float32) for k in grp]
|
| 2471 |
+
Xv: list = []
|
| 2472 |
+
Yv: list[list] = [[] for _ in grp]
|
| 2473 |
+
|
| 2474 |
+
def run(indices, train: bool) -> int:
|
| 2475 |
+
n_tok = 0
|
| 2476 |
+
for r0 in range(0, len(indices), micro):
|
| 2477 |
+
sub = indices[r0:r0 + micro]
|
| 2478 |
+
x = h[sub].to(device=dev, dtype=torch.float32)
|
| 2479 |
+
_set_weights(params, W_fp)
|
| 2480 |
+
xt = _capture_input(model, first, x).reshape(-1, d)
|
| 2481 |
+
ys = [xt @ W_fp[k].t() for k in grp]
|
| 2482 |
+
if solved_any:
|
| 2483 |
+
_set_weights(params, W_stu)
|
| 2484 |
+
xq = _capture_input(model, first, x).reshape(-1, d)
|
| 2485 |
+
else:
|
| 2486 |
+
xq = xt
|
| 2487 |
+
n_tok += xq.shape[0]
|
| 2488 |
+
if train:
|
| 2489 |
+
C.addmm_(xq.t(), xq)
|
| 2490 |
+
for j, y in enumerate(ys):
|
| 2491 |
+
G[j].addmm_(xq.t(), y)
|
| 2492 |
+
yy[j] += y.pow(2).sum(0)
|
| 2493 |
+
else:
|
| 2494 |
+
Xv.append(xq)
|
| 2495 |
+
for j, y in enumerate(ys):
|
| 2496 |
+
Yv[j].append(y)
|
| 2497 |
+
return n_tok
|
| 2498 |
+
|
| 2499 |
+
n_train = run(list(train_idx), True)
|
| 2500 |
+
n_val = run(list(eval_idx), False)
|
| 2501 |
+
Xv_t = torch.cat(Xv, 0)
|
| 2502 |
+
Yv_t = [torch.cat(parts, 0) for parts in Yv]
|
| 2503 |
+
return C, G, yy, Xv_t, Yv_t, n_train, n_val
|
| 2504 |
+
|
| 2505 |
+
@torch.no_grad()
|
| 2506 |
+
def _fit_module(self, name: str, qw, W_fp_t, C, G, yy, Xv, Yv):
|
| 2507 |
+
"""Algebraic fit of one projection; returns (decoded lattice weights, info)."""
|
| 2508 |
+
dev = self.device
|
| 2509 |
+
m, d = W_fp_t.shape
|
| 2510 |
+
if qw.packed is None:
|
| 2511 |
+
raise RuntimeError(f"{name}: no packed Q2_K payload cached (keep_packed missing)")
|
| 2512 |
+
q_np, s_np, o_np = _q2k_unpack(qw.packed, m, d)
|
| 2513 |
+
q = torch.from_numpy(q_np).to(dev)
|
| 2514 |
+
s = torch.from_numpy(s_np).to(dev)
|
| 2515 |
+
o = torch.from_numpy(o_np).to(dev)
|
| 2516 |
+
W_base = _q2k_decode(q, s, o)
|
| 2517 |
+
# The unpacked codes/scales must reproduce the bit-exact decoder.
|
| 2518 |
+
ref = qw.q.to(dev)
|
| 2519 |
+
tol = 1e-4 * max(float(ref.abs().max()), 1e-8)
|
| 2520 |
+
diff = float((W_base - ref).abs().max())
|
| 2521 |
+
if diff > tol:
|
| 2522 |
+
raise RuntimeError(
|
| 2523 |
+
f"{name}: Q2_K unpack disagrees with the bit-exact decoder "
|
| 2524 |
+
f"(max|diff|={diff:.3e} > {tol:.3e}); refusing to fit")
|
| 2525 |
+
del ref
|
| 2526 |
+
W_src = W_fp_t.to(self.round_dtype).float() if self.round_dtype is not None else W_fp_t
|
| 2527 |
+
|
| 2528 |
+
e_best = _row_err_gram(W_base, C, G, yy)
|
| 2529 |
+
v_best = _row_err_val(W_base, Xv, Yv)
|
| 2530 |
+
W_best = W_base
|
| 2531 |
+
e_base_sum = float(e_best.sum())
|
| 2532 |
+
v_base_sum = float(v_best.sum())
|
| 2533 |
+
yy_sum = float(yy.sum())
|
| 2534 |
+
yv_sum = float(Yv.pow(2).sum())
|
| 2535 |
+
n_taken = torch.zeros(m, dtype=torch.bool, device=dev)
|
| 2536 |
+
t0 = time.time()
|
| 2537 |
+
t_ls = 0.0
|
| 2538 |
+
for it in range(self.ls_iters):
|
| 2539 |
+
ts = time.time()
|
| 2540 |
+
s_ls, o_ls = _ls_fit_gram(C, G, q, s, o, self.ls_ridge, self.ls_row_chunk)
|
| 2541 |
+
if dev.type == "cuda":
|
| 2542 |
+
torch.cuda.synchronize(dev)
|
| 2543 |
+
t_ls += time.time() - ts
|
| 2544 |
+
s2, o2 = _snap_scales(s_ls, o_ls)
|
| 2545 |
+
W_c = _q2k_decode(q, s2, o2)
|
| 2546 |
+
e_c = _row_err_gram(W_c, C, G, yy)
|
| 2547 |
+
v_c = _row_err_val(W_c, Xv, Yv)
|
| 2548 |
+
take = (e_c <= e_best) & (v_c <= v_best)
|
| 2549 |
+
W_best = torch.where(take[:, None], W_c, W_best)
|
| 2550 |
+
e_best = torch.where(take, e_c, e_best)
|
| 2551 |
+
v_best = torch.where(take, v_c, v_best)
|
| 2552 |
+
n_taken |= take
|
| 2553 |
+
if self.verbose:
|
| 2554 |
+
self.log(f" {name} ls iter {it}: rows taken {int(take.sum())}/{m} "
|
| 2555 |
+
f"train_rel={(max(float(e_best.sum()), 0.0) / max(yy_sum, 1e-30)) ** 0.5:.4e}")
|
| 2556 |
+
if it + 1 < self.ls_iters:
|
| 2557 |
+
# next round: re-derive codes for the snapped scales, refit scales
|
| 2558 |
+
q = _rederive_codes(s2, o2, W_src)
|
| 2559 |
+
s, o = s2, o2
|
| 2560 |
+
info = {
|
| 2561 |
+
"rows": int(n_taken.sum()), "m": m,
|
| 2562 |
+
"train_before": (max(e_base_sum, 0.0) / max(yy_sum, 1e-30)) ** 0.5,
|
| 2563 |
+
"train_after": (max(float(e_best.sum()), 0.0) / max(yy_sum, 1e-30)) ** 0.5,
|
| 2564 |
+
"val_before": (v_base_sum / max(yv_sum, 1e-30)) ** 0.5,
|
| 2565 |
+
"val_after": (float(v_best.sum()) / max(yv_sum, 1e-30)) ** 0.5,
|
| 2566 |
+
"t_ls": t_ls, "t": time.time() - t0,
|
| 2567 |
+
}
|
| 2568 |
+
return W_best, info
|
| 2569 |
+
|
| 2570 |
+
@torch.no_grad()
|
| 2571 |
+
def _algebraic_fit(self, model, manager, block: int, h, train_idx: list[int]) -> None:
|
| 2572 |
+
dev = self.device
|
| 2573 |
+
mods = [m for m, _ in manager.modules]
|
| 2574 |
+
qws = [qw for _, qw in manager.modules]
|
| 2575 |
+
names = manager.names
|
| 2576 |
+
params = [m.parametrizations.weight.original for m in mods]
|
| 2577 |
+
W_fp = [p.data for p in params] # teacher weights, untouched until the end
|
| 2578 |
+
W_stu = list(W_fp) # student weights: fp until a group is solved
|
| 2579 |
+
for qw in qws:
|
| 2580 |
+
qw._defer = True # forward uses `original` directly
|
| 2581 |
+
t_all = time.time()
|
| 2582 |
+
try:
|
| 2583 |
+
groups, unused = self._discover_groups(model, manager, h)
|
| 2584 |
+
self.log(f"blk.{block}: algebraic fit: {len(groups)} input group(s) "
|
| 2585 |
+
+ " | ".join("+".join(names[k] for k in g) for g in groups)
|
| 2586 |
+
+ (f"; not called in forward (baseline kept): "
|
| 2587 |
+
f"{', '.join(names[k] for k in unused)}" if unused else ""))
|
| 2588 |
+
solved_any = False
|
| 2589 |
+
for grp in groups:
|
| 2590 |
+
tg = time.time()
|
| 2591 |
+
C, G, yy, Xv, Yv, n_train, n_val = self._collect_group_stats(
|
| 2592 |
+
model, mods, params, W_fp, W_stu, grp, h, train_idx,
|
| 2593 |
+
list(self._eval_idx), solved_any)
|
| 2594 |
+
t_stats = time.time() - tg
|
| 2595 |
+
for j, k in enumerate(grp):
|
| 2596 |
+
W_new, info = self._fit_module(
|
| 2597 |
+
names[k], qws[k], W_fp[k], C, G[j], yy[j], Xv, Yv[j])
|
| 2598 |
+
W_stu[k] = W_new
|
| 2599 |
+
self.log(
|
| 2600 |
+
f"blk.{block}: {names[k]:<34s} out-rel train "
|
| 2601 |
+
f"{100 * info['train_before']:.2f}%->{100 * info['train_after']:.2f}% "
|
| 2602 |
+
f"held-out {100 * info['val_before']:.2f}%->{100 * info['val_after']:.2f}% "
|
| 2603 |
+
f"rows {info['rows']}/{info['m']} ls {info['t_ls']:.1f}s "
|
| 2604 |
+
f"(fit {info['t']:.1f}s)")
|
| 2605 |
+
self.log(f"blk.{block}: group stats {n_train} fit + {n_val} held-out tokens "
|
| 2606 |
+
f"in {t_stats:.1f}s")
|
| 2607 |
+
del C, G, yy, Xv, Yv
|
| 2608 |
+
if dev.type == "cuda":
|
| 2609 |
+
torch.cuda.empty_cache()
|
| 2610 |
+
solved_any = True
|
| 2611 |
+
for k in unused:
|
| 2612 |
+
W_stu[k] = qws[k].get_q(W_fp[k]).to(dev)
|
| 2613 |
+
finally:
|
| 2614 |
+
_set_weights(params, W_fp)
|
| 2615 |
+
for qw in qws:
|
| 2616 |
+
qw._defer = False
|
| 2617 |
+
# Install: the trained fp weight *is* the decoded lattice point, so the
|
| 2618 |
+
# converter's re-quantization reproduces it (checked after this by the
|
| 2619 |
+
# final refresh in train_block).
|
| 2620 |
+
for k, (p, qw) in enumerate(zip(params, qws)):
|
| 2621 |
+
p.copy_(W_stu[k])
|
| 2622 |
+
qw.q = W_stu[k]
|
| 2623 |
+
qw.err = None
|
| 2624 |
+
qw._dev_q = None
|
| 2625 |
+
qw._dev_err = None
|
| 2626 |
+
qw.packed = None
|
| 2627 |
+
self.log(f"blk.{block}: algebraic fit finished in {time.time() - t_all:.0f}s")
|
| 2628 |
+
|
| 2629 |
+
def _train(self, model, manager, norm_params, block: int, h: "_ActivationBuffer",
|
| 2630 |
+
targets: "_ActivationBuffer") -> None:
|
| 2631 |
+
"""Closed-form least-squares QAT of one block (no optimizer, no gradients)."""
|
| 2632 |
+
if not manager.modules:
|
| 2633 |
+
self.log(f"blk.{block}: no trainable projections; skipping")
|
| 2634 |
+
return
|
| 2635 |
for p in model.parameters():
|
| 2636 |
p.requires_grad_(False)
|
| 2637 |
+
model.eval()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2638 |
n = h.shape[0]
|
|
|
|
|
|
|
|
|
|
| 2639 |
eval_set = set(self._eval_idx)
|
| 2640 |
train_idx = [i for i in range(n) if i not in eval_set] or list(range(n))
|
| 2641 |
+
tq = time.time()
|
| 2642 |
+
manager.refresh() # real SMQ quantization; also caches the packed payloads
|
| 2643 |
+
self.log(f"blk.{block}: initial SMQ quantization of {len(manager.modules)} tensors "
|
| 2644 |
+
f"took {time.time() - tq:.0f}s")
|
| 2645 |
+
self._log_weight_rmse(block, manager, "at start (SMQ quantization error)")
|
| 2646 |
+
self._log_eval(block, model, h, targets, "BASELINE, plain SMQ before training")
|
| 2647 |
+
prev = torch.get_float32_matmul_precision()
|
| 2648 |
+
torch.set_float32_matmul_precision("highest") # no TF32 in normal equations
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2649 |
try:
|
| 2650 |
+
self._algebraic_fit(model, manager, block, h, train_idx)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2651 |
finally:
|
| 2652 |
+
torch.set_float32_matmul_precision(prev)
|
|
|
|
| 2653 |
gc.collect()
|
| 2654 |
if torch.cuda.is_available():
|
| 2655 |
torch.cuda.empty_cache()
|
| 2656 |
+
self._log_eval(block, model, h, targets,
|
| 2657 |
+
"ALGEBRAIC, fitted lattice before re-quantization")
|
| 2658 |
|
| 2659 |
def _load_saved(self, model, block: int, sd: dict) -> int:
|
| 2660 |
"""Copy a saved checkpoint's tensors into the model originals and norms."""
|
|
|
|
| 3062 |
offload_threshold: int = 64,
|
| 3063 |
quant_workers: int | None = None,
|
| 3064 |
verbose: bool = False,
|
| 3065 |
+
ls_iters: int = 2,
|
| 3066 |
+
ls_ridge: float = 1.0e-3,
|
| 3067 |
+
ls_row_chunk: int = 0,
|
| 3068 |
) -> int:
|
| 3069 |
+
"""Block-wise *algebraic* QAT against SMQ's real Q2_K quantizer.
|
| 3070 |
+
|
| 3071 |
+
No optimizer: each projection's Q2_K scales/offsets are solved in closed form
|
| 3072 |
+
(least squares on the layer output, Gram-matrix normal equations), snapped to
|
| 3073 |
+
the Q2_K lattice and row-guarded. ``ls_iters`` = solve/re-derive-codes rounds,
|
| 3074 |
+
``ls_ridge`` = proximal ridge toward the current scales (relative to a unit
|
| 3075 |
+
diagonal), ``ls_row_chunk`` = rows per batched solve (0 = auto). The legacy
|
| 3076 |
+
optimizer arguments below are kept so existing callers do not break, but are
|
| 3077 |
+
ignored.
|
| 3078 |
|
| 3079 |
``blocks`` is (lo, hi) with hi exclusive, exactly like the reference.
|
| 3080 |
``adaptive_step`` continues each block with no step limit until the
|
|
|
|
| 3134 |
log(f"QAT: tensor-type {name}={tt} ignored (SMQ emits Q2_K only)")
|
| 3135 |
log(f"QAT: {gguf_path}")
|
| 3136 |
log(f"QAT: plan = {n_quant} Q2_K tensors")
|
| 3137 |
+
log(f"QAT: algebraic least-squares fit (ls_iters={ls_iters}, ls_ridge={ls_ridge:g}); "
|
| 3138 |
+
"optimizer options (lr, steps, grad_accum, requant_*, norms, ...) are accepted but unused")
|
| 3139 |
log(f"QAT: blocks {lo}..{hi - 1} of {n_real}")
|
| 3140 |
if n_nextn:
|
| 3141 |
log(
|
|
|
|
| 3180 |
seed=seed,
|
| 3181 |
verbose=verbose,
|
| 3182 |
log=log,
|
| 3183 |
+
ls_iters=ls_iters,
|
| 3184 |
+
ls_ridge=ls_ridge,
|
| 3185 |
+
ls_row_chunk=ls_row_chunk,
|
| 3186 |
)
|
| 3187 |
h: _ActivationBuffer | None = None
|
| 3188 |
for b in range(lo, hi):
|