Upload 2 files
Browse filesFiles changed (2)
- smq_qat.py+425-129
- train_smq_qat.py+24-3
66 unmodified lines6768697071722 unmodified lines75767778798021 unmodified lines10210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213372 unmodified lines2062072082092102111 unmodified line2132142152162172182192202211 unmodified line2232242252262272282292302312322332342352362372382392402412422 unmodified lines2452462472482492502512522532542552562572582592602612622632642651 unmodified line267268269270271272273274275276277278279280281282283284285286287288289290291292165 unmodified lines45845946046146246346446537 unmodified lines5035045055065075083 unmodified lines5125135145155165175185195205215225235242 unmodified lines527528529530531532288 unmodified lines8218228238248258265 unmodified lines83283383483583683760 unmodified lines898899900901902903904905906907908909592 unmodified lines15021503150415051506150715083 unmodified lines151215131514151515161517151824 unmodified lines154315441545154615471548154915501551155215531554155515561557155 unmodified lines17131714171517161717171817191720172117221723172417259 unmodified lines17351736173717381739174017413 unmodified lines17451746174717481749175029 unmodified lines17801781178217831784178517862 unmodified lines178917901791179217931794179562 unmodified lines1858185918601861186218631864186518661867186818691870187118721873187418751876187723 unmodified lines190119021903190419051906190719081909191019111912191314 unmodified lines19281929193019311932193319341935193619371938193919401941194219437 unmodified lines195119521953195419551956195712 unmodified lines19701971197219731974197519764 unmodified lines1981198219831984198519861987198819891990199119928 unmodified lines20012002200320042005200611 unmodified lines20182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120423 unmodified lines204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720683 unmodified lines20722073207420752076207720782079118 unmodified lines21982199220022012202220322042205220622072208220939 unmodified lines22492250225122522253225422557 unmodified lines226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622978 unmodified lines230623072308230923102311231259 unmodified lines23722373237423752376237723784 unmodified lines23832384238523862387238854 unmodified lines24432444244524462447244824496 unmodified lines2456245724582459246024611 unmodified line24632464246524662467246824692470247124722473247424758 unmodified lines248424852486248724882489249035 unmodified lines2526252725282529253025312532253325342535253625372 unmodified lines25402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256630 unmodified lines259725982599260026012602260366 unmodified linesimport gcimport jsonimport osimport randomimport re2 unmodified linesimport sysimport tempfileimport timefrom pathlib import Pathfrom typing import Any21 unmodified lines# ---------------------------------------------------------------------------class _ActivationBuffer:"""Holds [N, S, D] bf16 activations in RAM or memory-mapped on disk."""def __init__(self, shape: tuple[int, ...], mmap_path: Path | None = None):self.shape = tuple(shape)self.mmap_path = mmap_pathif mmap_path is not None:mmap_path.parent.mkdir(parents=True, exist_ok=True)self._arr = np.memmap(mmap_path, dtype=np.uint16, mode="w+", shape=self.shape)self._tensor = Noneelse:self._arr = Noneself._tensor = torch.empty(self.shape, dtype=torch.bfloat16)def __getitem__(self, idx) -> "torch.Tensor":if self._tensor is not None:return self._tensor[idx]sub = np.array(self._arr[idx], copy=True)return torch.from_numpy(sub).view(torch.bfloat16)def __setitem__(self, idx, val: "torch.Tensor") -> None:val_cpu = val.detach().to(device="cpu", dtype=torch.bfloat16).contiguous()if self._tensor is not None:self._tensor[idx] = val_cpuelse:self._arr[idx] = val_cpu.view(torch.uint16).numpy()def flush(self) -> None:if self._arr is not None:72 unmodified linesW: "torch.Tensor",importance=None,device=None,) -> "torch.Tensor":"""Fake-quant *W* with the real SMQ quantizer (numpy engine, CPU).1 unmodified linein numpy, and the decoded weight moves back to *W*'s device (or to``device`` when given, e.g. "cpu" to keep the cache off the GPU). SMQ hasno torch kernels, so this is the faithful round-trip."""rows, cols = W.shaperec = quantize_dequantize(W.detach().float().cpu().numpy(), importance)return torch.from_numpy(np.ascontiguousarray(rec)).to(device=W.device if device is None else device, dtype=W.dtype)1 unmodified lineclass QatWeight(nn.Module):"""Straight-through fake-quant parametrization around a linear weight."""def __init__(self, importance=None, offload: bool = False):super().__init__()self.importance = importanceself.offload = offload # keep the decoded cache in (pinned) CPU RAMself.q = Nonedef get_q(self, like: "torch.Tensor") -> "torch.Tensor | None":"""The decoded cache on *like*'s device (a transient copy when offloaded)."""q = self.qif q is None or q.device == like.device:return qreturn q.to(like.device, non_blocking=True)def forward(self, W: "torch.Tensor") -> "torch.Tensor":if self.q is None or self.q.shape != W.shape:self.refresh(W)return W + (self.get_q(W) - W).detach()2 unmodified linesdef refresh(self, W: "torch.Tensor") -> None:"""Re-quantize *W* with the real SMQ engine and cache the decoded copy."""if self.offload:q = quantize_dequantize_torch(W, self.importance, device="cpu")try:q = q.pin_memory()except Exception: # noqa: BLE001 - pinned RAM unavailable: plain CPU tensorpassself.q = qelse:self.q = quantize_dequantize_torch(W, self.importance)class QatManager:"""Attaches fake-quant parametrizations and refreshes their caches."""def __init__(self, offload_q: bool = False):self.offload_q = offload_qself.modules: list[tuple["nn.Module", QatWeight]] = []self.names: list[str] = [] # parallel to .modules (for logging)1 unmodified lineif not isinstance(module, nn.Linear):return Falseif P.is_parametrized(module, "weight"):return TrueP.register_parametrization(module, "weight", QatWeight(importance, self.offload_q))self.modules.append((module, module.parametrizations.weight[0]))self.names.append(name or f"module{len(self.modules) - 1}")return Truedef refresh(self) -> None:for module, qw in self.modules:qw.refresh(module.parametrizations.weight.original)def originals(self):return [m.parametrizations.weight.original for m, _ in self.modules]def weight_penalty(self, device: "torch.device | str | None" = None) -> "torch.Tensor":"""Mean relative squared weight-space quant error ||W-Q(W)||^2/||W||^2."""total = Nonecount = 0for module, qw in self.modules:W = module.parametrizations.weight.originalq = qw.get_q(W)if q is None or q.shape != W.shape:continuedenom = W.pow(2).mean() + 1.0e-12165 unmodified linesreturn Nonedef _tensors_by_name(reader) -> dict[str, Any]:return {ti.name: ti for ti in reader.tensors}def total_blocks(reader) -> int:37 unmodified lineskey_dim = state_size * group_count (q and k rows), value_dim = inner_size(v and z rows), head_v_dim = inner_size / time_step_rank."""arch = _read_arch(reader)vals = (_meta_scalar(reader, f"{arch}.ssm.conv_kernel"),3 unmodified lines_meta_scalar(reader, f"{arch}.ssm.inner_size"),)if None in vals:return Noneconv_kernel, state, group, tstep, inner = (int(v) for v in vals)if group <= 0 or tstep <= 0 or inner % tstep:raise ValueError(f"{arch}.ssm metadata inconsistent: inner_size={inner} time_step_rank={tstep}")return {"conv_kernel": conv_kernel,"head_k_dim": state,"num_k_heads": group,2 unmodified lines"key_dim": state * group,"value_dim": inner,}def _layer_is_recurrent(reader, block: int) -> bool:288 unmodified linesloudly. NextN/MTP draft-head tensors ("blk.<N>.nextn.*") are skipped:llama.cpp never runs the draft layers."""arch = _read_arch(reader)ssm = _ssm_dims(reader)prefix = f"blk.{block}."5 unmodified linesif suffix.startswith("nextn."):continuespecs.append(_build_spec(ti.name, suffix, smqc.tensor_ggml_shape(ti), arch, ssm))return specs60 unmodified lines"output_norm.weight", ["norm.weight"],lambda a: [a], lambda h: h[0], "aux")return outreturn outdef _gguf_f32(reader, name: str) -> np.ndarray:"""Dequantized f32 numpy view of one GGUF tensor (physical shape)."""_gguf, _reader_cls, dequantize_fn, *_rest = smqc.load_gguf()return smqc.load_tensor_f32(_tensors_by_name(reader)[name], dequantize_fn)592 unmodified lines@torch.no_grad()def _forward_pre_norm(model, x: "torch.Tensor", autocast_dtype) -> "torch.Tensor":"""Raw output of the (single) decoder layer, before the model's final norm."""holder = {}3 unmodified lineslayer = _get_decoder_layers(model)[0]h = layer.register_forward_hook(hook)try:ctx = torch.autocast(device_type=x.device.type, dtype=autocast_dtype)with ctx:model(inputs_embeds=x, use_cache=False)finally:24 unmodified linesdtype,micro_batch: int,out_mmap: Path | None = None,) -> "_ActivationBuffer":n = h.shape[0]buf: _ActivationBuffer | None = Nonefor r0 in range(0, n, micro_batch):r1 = min(n, r0 + micro_batch)x = h[r0:r1].to(device=device, dtype=dtype)y = fn(x).to(dtype=torch.bfloat16).cpu()if buf is None:buf = _ActivationBuffer((n, *y.shape[1:]), mmap_path=out_mmap)buf[r0:r1] = yassert buf is not Nonebuf.flush()155 unmodified linesadaptive_step: bool = False,adaptive_rel: float = 0.05,micro_batch: int = 4,requant_every: int = 0,train_types: set[str] | None = None,excluded_types: set[str] | None = None,grad_checkpointing: bool = True,propagate: str = "qat",offload_threshold: int = 64,offload_q="auto",log=print,):self.reader = reader9 unmodified linesself.adaptive_step = adaptive_stepself.adaptive_rel = adaptive_relself.micro_batch = micro_batchself.requant_every = requant_everyself.train_types = train_typesself.excluded_types = excluded_types or set()self.grad_checkpointing = grad_checkpointing3 unmodified lines# estimated VRAM need would not fit; True/False force it.self.offload_q = offload_qself._offload_q_now = Falseself.log = logself.autocast_dtype = torch.bfloat16self.trained_dir = self.work_dir / "trained"29 unmodified linesreturn targetsdef _attached(self, model, block: int):manager = QatManager(offload_q=self._offload_q_now)layer = _get_decoder_layers(model)[0]for gguf_name, hf_name in self._trainable(block):try:2 unmodified linescontinueif not isinstance(module, nn.Linear):continuemanager.attach(module, self._importance(gguf_name, hf_name), name=hf_name)return managerdef _collect_norm_params(self, model, block: int) -> list["nn.Parameter"]:62 unmodified linespassif h is None:raise RuntimeError("internal: block 0 activations must be built before train_block")_drop_embedding(model)use_mmap = self._use_mmap(h.shape[0])targets_mmap = self.work_dir / f"tmp_targets_blk{block}.bin" if use_mmap else Noneout_mmap = self.work_dir / f"tmp_act_blk{block + 1}.bin" if use_mmap else None# 1. Full-precision targets: the raw (pre-norm) block output, so the# trained block reproduces exactly what is chained into the next one.self.log(f"blk.{block}: computing full-precision targets ({h.shape[0]} seqs)")targets = _batched_forward(lambda x: _forward_pre_norm(model, x, self.autocast_dtype),h,self.device,torch.float32,self.micro_batch,out_mmap=targets_mmap,)gc.collect()if torch.cuda.is_available():23 unmodified lines) from eself._save(model, manager, norm_params, block, saved)# 2. Propagate corpus activations through the (fake-quantized) block.self.log(f"blk.{block}: propagating activations ({self.propagate})")if self.propagate != "full" and manager.modules:manager.refresh()self._log_weight_rmse(block, manager, "after final re-quantization (trained W vs Q(W))")model.eval()if manager.modules:self._log_eval(block, model, h, targets, "FINAL, trained + re-quantized")out = _batched_forward(lambda x: _forward_pre_norm(model, x, self.autocast_dtype),h,14 unmodified linestorch.cuda.empty_cache()return outdef _eval_block(self, model, h, targets, k: int = 8):"""(rmse, rel, cosine) of the block output vs the fp32 targets on the firstk sequences, using the same forward that produced the targets."""k = min(k, h.shape[0])micro = max(1, min(self.micro_batch, k))se = ys = cos_sum = 0.0cnt = ncos = 0with torch.no_grad():for r0 in range(0, k, micro):idx = list(range(r0, min(k, r0 + micro)))x = h[idx].to(device=self.device, dtype=torch.float32)y = targets[idx].to(device=self.device, dtype=torch.float32)pred = _forward_pre_norm(model, x, self.autocast_dtype).float()7 unmodified linesdef _log_eval(self, block: int, model, h, targets, label: str) -> None:rmse, rel, cos = self._eval_block(model, h, targets)self.log(f"blk.{block}: block-output error {label}: out_rmse={rmse:.3e} "f"(rel {100 * rel:.2f}%) cos={cos:.5f} [first 8 seqs]")def _log_weight_rmse(self, block: int, manager, label: str) -> None:if not manager.modules:12 unmodified linesp.requires_grad_(True)param_groups = [{"params": quant_params, "lr": self.lr, "weight_decay": self.weight_decay}]if norm_params:param_groups.append({"params": norm_params, "lr": self.lr, "weight_decay": 0.0})# fused (CUDA) or per-tensor AdamW: the default multi-tensor path needs a# full extra copy of the optimizer state as scratch inside step().opt = None4 unmodified linesopt = Noneif opt is None:opt = torch.optim.AdamW(param_groups, betas=(0.9, 0.95), foreach=False)scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=max(1, self.steps), eta_min=self.lr * 0.05)n = h.shape[0]micro = max(1, min(self.micro_batch, n))rng = random.Random(1234 + block)if manager.modules:tq = time.time()manager.refresh() # the same quantization the first forward would do lazily8 unmodified lines"at the final re-quantization (w_rmse below will drift upward). ""Use requant_every=N for in-loop re-quantization.")space = _SpaceStop()if self.adaptive_step:hint = ("press space to stop early and keep the current weights"11 unmodified linestry:step = 0while self.adaptive_step or step < self.steps:idx = rng.sample(range(n), micro)x = h[idx].to(device=self.device, dtype=torch.float32)y = targets[idx].to(device=self.device, dtype=torch.float32)ctx = torch.autocast(device_type=self.device.type, dtype=self.autocast_dtype)with ctx:pred = _forward_layer_train(model, x)pred_f = pred.float()mse = F.mse_loss(pred_f, y)loss = msecos_part = pen_part = None # weighted terms, for the log line onlyif self.cosine_lambda:cos_loss = (1.0 - F.cosine_similarity(pred_f, y, dim=-1)).mean()cos_part = self.cosine_lambda * cos_lossloss = loss + cos_partif self.weight_rmse_lambda:pen = manager.weight_penalty(device=loss.device).to(dtype=torch.float32)pen_part = self.weight_rmse_lambda * penloss = loss + pen_partloss.backward()torch.nn.utils.clip_grad_norm_(all_params, 1.0)opt.step()scheduler.step()3 unmodified linesmanager.refresh()self.log(f"blk.{block}: step {step + 1}: re-quantized {len(manager.modules)} "f"tensors in {time.time() - tq:.0f}s")model.train()with torch.no_grad():out_rmse = float(mse.detach().sqrt())y_rms = float(y.pow(2).mean().sqrt())out_rel = out_rmse / max(y_rms, 1e-30)at_end = not self.adaptive_step and step + 1 == self.stepsif (step + 1) % log_every == 0 or at_end:with torch.no_grad():w_rmse, w_rel, _rows = manager.weight_rmse()terms = f"mse {float(mse.detach()):.2e}"if cos_part is not None:terms += f" + cos {float(cos_part.detach()):.2e}"if pen_part is not None:terms += f" + wpen {float(pen_part.detach()):.2e}"total = "" if self.adaptive_step else f"/{self.steps}"self.log(f"blk.{block}: step {step + 1}{total} loss={float(loss.detach()):.6e} "f"[{terms}] out_rmse={out_rmse:.3e} (rel {100 * out_rel:.1f}%) "f"w_rmse={w_rmse:.3e} (rel {100 * w_rel:.2f}%) "f"lr={scheduler.get_last_lr()[0]:.2e} ({(time.time() - t0) / (step + 1):.2f}s/step)"3 unmodified lines"keeping the current weights")breakif self.adaptive_step and out_rel < self.adaptive_rel:# Confirm the minibatch estimate on a fixed evaluation set# before ending the block early.was_training = model.trainingmodel.eval()try:118 unmodified linesreturn indexdef _load_trained(path: Path | None, key: str):"""One trained tensor as float32 numpy (None if not trained)."""if path is None:return Nonefrom safetensors import safe_opentry:with safe_open(str(path), framework="np") as f:return np.asarray(f.get_tensor(key), dtype=np.float32)39 unmodified lines"""import gguf_gguf_py, _reader_cls, _dequant, _wr, _qt, GGUFValueType, _end = smqc.load_gguf()index = _index_trained(trained_dir)if not index:7 unmodified linesspec_by_gname[spec.gguf] = specmodel_specs = _model_level_specs(reader)checks: dict[str, np.ndarray] = {}for ti in reader.tensors:spec = model_specs.get(ti.name) or spec_by_gname.get(ti.name)arr = Noneblk = _block_of(ti.name)if spec is not None and blk is not None:vals = [_load_trained(index.get((blk, h)), h) for h in spec.hf]if all(v is not None for v in vals):arr = spec.forward(vals)if arr is None:smqc.add_tensor_passthrough(writer, ti, reader)continueshape = smqc.tensor_ggml_shape(ti)if len(shape) == 1:writer.add_tensor(ti.name, np.ascontiguousarray(arr.reshape(-1), dtype=np.float32))else:# physical layout: rows = ne[1] (output), cols = ne[0] (input).# gguf-py takes the numpy array as-is and REVERSES its shape to get# ne, so the (ne[1], ne[0]) array is passed unchanged (never .T).# float16 maps to GGML F16 in gguf-py.if arr.shape[0] != shape[1] or arr.shape[1] != shape[0]:raise ValueError(f"trained tensor {ti.name!r} shape {arr.shape} does not "f"match GGUF ne={shape}")arr16 = np.ascontiguousarray(arr, dtype=np.float16)writer.add_tensor(ti.name, arr16)if len(checks) < 6:checks[ti.name] = np.array(arr16[:64, :64])written += 1_copy_metadata_f16(reader, writer, GGUFValueType)writer.write_header_to_file()writer.write_kv_data_to_file()8 unmodified lines"""Re-open the written GGUF: every tensor must keep its source shape, and afew trained tensors must read back bit-exactly (catches transposed layouts,including square matrices whose shape alone would look right)."""_g, reader_cls, *_rest = smqc.load_gguf()out = reader_cls(str(output))src = {t.name: tuple(int(x) for x in smqc.tensor_ggml_shape(t)) for t in reader.tensors}bad = []59 unmodified linesdef _disk_problems(reader, output: Path, work_dir: Path, lo: int, hi: int,tmp_dir=None) -> list[str]:"""Fail BEFORE hours of training if the disks cannot hold trained + exported data."""gib = 2 ** 30trained, export = _export_plan(reader, lo, hi)4 unmodified linesitems = [("trained weights (fp32)", work_dir, trained),("export spool file", tmp, export),("exported GGUF", Path(output).resolve().parent, export)]def existing(path) -> Path:pth = Path(path).resolve()54 unmodified linesadaptive_step: bool = False,adaptive_rel: float = 0.05,micro_batch: int = 4,requant_every: int = 0,train_types: set[str] | None = None,tensor_type: list[tuple[str, str]] | None = None,grad_checkpointing: bool = True,6 unmodified linesdevice: str = "cuda",validate: bool = True,offload_q="auto",) -> int:"""Block-wise QAT against SMQ's real Q2_K quantizer.1 unmodified line``adaptive_step`` continues each block with no step limit until theblock-output relative error is below ``adaptive_rel`` (0.05 = 5%) or space ispressed; ``steps`` is then only the cosine LR schedule horizon. Without theflag, ``steps`` remains the fixed number of steps per block.Returns the trained-tensor count from the export."""gguf_path = Path(gguf_path)output = Path(output)log = print_gguf_py, reader_cls, _deq, *_rest = smqc.load_gguf()reader = reader_cls(str(gguf_path))arch = _read_arch(reader)n_blocks = total_blocks(reader)8 unmodified lines# the (slow) corpus load and before any training starts.problems += preflight(reader, (lo, hi), log=log)_wd = Path(work_dir) if work_dir else output.parent / (output.stem + ".qat_work")problems += _disk_problems(reader, output, _wd, lo, hi)_raise_if_problems(problems)if not torch.cuda.is_available() and device.startswith("cuda"):raise RuntimeError("CUDA requested but not available; use --device cpu")35 unmodified linesadaptive_step=adaptive_step,adaptive_rel=adaptive_rel,micro_batch=micro_batch,requant_every=requant_every,train_types=train_types,excluded_types=excluded,grad_checkpointing=grad_checkpointing,propagate=propagate,offload_q=offload_q,log=log,)h: _ActivationBuffer | None = None2 unmodified lineshf_dir = work_dir / f"hf_blk{b}"prepare_hf_partial(reader, hf_dir, b, log=log)if h is None:# Block 0 (or a mid-model start): embed the corpus through the# real embedding table.model = _load_block_model(hf_dir, trainer.device, keep_embedding=True)emb = model.get_input_embeddings()if emb is None:raise RuntimeError("cannot embed the corpus: model has no input embedding")emb_mmap = work_dir / f"tmp_act_blk{b}.bin" if trainer._use_mmap(seqs.shape[0]) else Nonewith torch.no_grad():for r0 in range(0, seqs.shape[0], micro_batch):r1 = min(seqs.shape[0], r0 + micro_batch)batch_h = emb(seqs[r0:r1].to(trainer.device)).to(dtype=torch.bfloat16).cpu()if h is None:h = _ActivationBuffer((seqs.shape[0], *batch_h.shape[1:]), mmap_path=emb_mmap)h[r0:r1] = batch_hassert h is not Noneh.flush()log(f"blk.{b}: embedded corpus -> {h.shape} (mmap={emb_mmap is not None})")del emb, modelgc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()h = trainer.train_block(b, h, hf_dir)log(f"blk.{b}: done in {time.time() - t0:.0f}s")if not keep_block_dirs:30 unmodified linesap.add_argument("--tmp-dir", type=Path,help="where the export spools tensor data (default: TMPDIR or next to --output)")args = ap.parse_args()_g, _rc, *_r = smqc.load_gguf()_reader = _rc(str(args.gguf))if args.export_trained:if not args.output:66 unmodified lines676869707172732 unmodified lines7677787980818221 unmodified lines10410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615772 unmodified lines2302312322332342352361 unmodified line2382392402412422432442452462472482492502512521 unmodified line2542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922 unmodified lines2952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283291 unmodified line331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383165 unmodified lines54955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857937 unmodified lines6176186196206216226236246253 unmodified lines6296306316326336346356366376386396406416422 unmodified lines645646647648649650651652288 unmodified lines9419429439449459469479489499505 unmodified lines95695795895996096196260 unmodified lines1023102410251026102710281029103010311032103310341035103610371038103910401041104210431044592 unmodified lines163716381639164016411642164316443 unmodified lines1648164916501651165216531654165524 unmodified lines168016811682168316841685168616871688168916901691169216931694169516961697155 unmodified lines185318541855185618571858185918601861186218631864186518661867186818691870187118729 unmodified lines188218831884188518861887188818891890189118921893189418953 unmodified lines189919001901190219031904190529 unmodified lines19351936193719381939194019412 unmodified lines19441945194619471948194919501951195262 unmodified lines2015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204023 unmodified lines2064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208614 unmodified lines210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221237 unmodified lines213121322133213421352136213712 unmodified lines215021512152215321542155215621572158215921604 unmodified lines21652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322048 unmodified lines22132214221522162217221822192220222111 unmodified lines223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122823 unmodified lines228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723083 unmodified lines23122313231423152316231723182319118 unmodified lines243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246239 unmodified lines25022503250425052506250725087 unmodified lines25162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725588 unmodified lines256725682569257025712572257359 unmodified lines263326342635263626372638263926404 unmodified lines2645264626472648264926502651265226532654265526562657265826592660266154 unmodified lines2716271727182719272027212722272327242725272627276 unmodified lines273427352736273727382739274027411 unmodified line27432744274527462747274827492750275127522753275427552756275727582759276027612762276327648 unmodified lines27732774277527762777277827792780278135 unmodified lines281728182819282028212822282328242825282628272828282928302831283228332834283528362 unmodified lines28392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286230 unmodified lines289328942895289628972898289966 unmodified linesimport gcimport jsonimport mathimport osimport randomimport re2 unmodified linesimport sysimport tempfileimport timefrom concurrent.futures import ThreadPoolExecutorfrom pathlib import Pathfrom typing import Any21 unmodified lines# ---------------------------------------------------------------------------_MMAP_NUMPY_DTYPE = {} if torch is None else {torch.bfloat16: np.uint16, # bf16 has no numpy dtype: store raw bitstorch.float16: np.float16,torch.float32: np.float32,}class _ActivationBuffer:"""Holds [N, S, D] activations in RAM or memory-mapped on disk.``dtype`` defaults to bf16 for the chained block activations, but targetsare stored in fp32 so the distillation signal keeps full precision."""def __init__(self, shape: tuple[int, ...], mmap_path: Path | None = None,dtype: "torch.dtype | None" = None):if dtype is None:dtype = torch.bfloat16if dtype not in _MMAP_NUMPY_DTYPE:raise ValueError(f"unsupported activation-buffer dtype {dtype}")self.shape = tuple(shape)self.mmap_path = mmap_pathself.dtype = dtypeself._bf16 = dtype == torch.bfloat16if mmap_path is not None:mmap_path.parent.mkdir(parents=True, exist_ok=True)self._arr = np.memmap(mmap_path, dtype=_MMAP_NUMPY_DTYPE[dtype], mode="w+", shape=self.shape)self._tensor = Noneelse:self._arr = Noneself._tensor = torch.empty(self.shape, dtype=dtype)def __getitem__(self, idx) -> "torch.Tensor":if self._tensor is not None:return self._tensor[idx]sub = np.array(self._arr[idx], copy=True)out = torch.from_numpy(sub)return out.view(torch.bfloat16) if self._bf16 else outdef __setitem__(self, idx, val: "torch.Tensor") -> None:val_cpu = val.detach().to(device="cpu", dtype=self.dtype).contiguous()if self._tensor is not None:self._tensor[idx] = val_cpuelif self._bf16:self._arr[idx] = val_cpu.view(torch.uint16).numpy()else:self._arr[idx] = val_cpu.numpy()def flush(self) -> None:if self._arr is not None:72 unmodified linesW: "torch.Tensor",importance=None,device=None,round_dtype: "torch.dtype | None" = None,) -> "torch.Tensor":"""Fake-quant *W* with the real SMQ quantizer (numpy engine, CPU).1 unmodified linein numpy, and the decoded weight moves back to *W*'s device (or to``device`` when given, e.g. "cpu" to keep the cache off the GPU). SMQ hasno torch kernels, so this is the faithful round-trip.``round_dtype`` first rounds *W* onto the storage lattice the export uses(``torch.float16`` for trained 2-D projections), so training optimizes thesame values the converter will actually quantize."""wc = W.detach().float()if round_dtype is not None:wc = wc.to(round_dtype).float()rec = quantize_dequantize(wc.cpu().numpy(), importance)return torch.from_numpy(np.ascontiguousarray(rec)).to(device=W.device if device is None else device, dtype=W.dtype)1 unmodified lineclass QatWeight(nn.Module):"""Straight-through fake-quant parametrization around a linear weight."""def __init__(self, importance=None, offload: bool = False,round_dtype: "torch.dtype | None" = None,cache_device: bool | None = None):super().__init__()self.importance = importanceself.offload = offload # keep the decoded cache in (pinned) CPU RAMself.round_dtype = round_dtype# A persistent device copy avoids one H2D per forward, but it consumes# the VRAM that offloading was chosen to free -- so cache only when the# decoded weights are not being offloaded.self.cache_device = (not offload) if cache_device is None else bool(cache_device)self.q = Noneself._dev_q = None# Set while a parametrization is being registered: the registration# itself calls forward() once, and quantizing there would serialize an# extra full pass over every tensor before manager.refresh().self._defer = Falsedef get_q(self, like: "torch.Tensor") -> "torch.Tensor | None":"""The decoded cache on *like*'s device (cached when memory allows)."""q = self.qif q is None or q.device == like.device:return qif not self.cache_device:return q.to(like.device, non_blocking=True)if self._dev_q is not None and self._dev_q.device == like.device:return self._dev_qself._dev_q = q.to(like.device, non_blocking=True)return self._dev_qdef forward(self, W: "torch.Tensor") -> "torch.Tensor":if self._defer:return Wif self.q is None or self.q.shape != W.shape:self.refresh(W)return W + (self.get_q(W) - W).detach()2 unmodified linesdef refresh(self, W: "torch.Tensor") -> None:"""Re-quantize *W* with the real SMQ engine and cache the decoded copy."""if self.offload:q = quantize_dequantize_torch(W, self.importance, device="cpu", round_dtype=self.round_dtype)try:q = q.pin_memory()except Exception: # noqa: BLE001 - pinned RAM unavailable: plain CPU tensorpassself.q = qelse:self.q = quantize_dequantize_torch(W, self.importance, round_dtype=self.round_dtype)self._dev_q = None@torch.no_grad()def fresh_q(self, W: "torch.Tensor") -> "torch.Tensor":"""Quantize the *current* W (not the cached one)."""return quantize_dequantize_torch(W, self.importance, device=W.device, round_dtype=self.round_dtype)class QatManager:"""Attaches fake-quant parametrizations and refreshes their caches."""def __init__(self, offload_q: bool = False,round_dtype: "torch.dtype | None" = None,max_workers: int | None = None):self.offload_q = offload_qself.round_dtype = round_dtype# SMQ is numpy + per-tensor; independent tensors quantize in parallel.self.max_workers = max_workers or max(1, min(4, os.cpu_count() or 1))self.modules: list[tuple["nn.Module", QatWeight]] = []self.names: list[str] = [] # parallel to .modules (for logging)1 unmodified lineif not isinstance(module, nn.Linear):return Falseif P.is_parametrized(module, "weight"):qw = module.parametrizations.weight[0]if all(module is not m for m, _ in self.modules):self.modules.append((module, qw))self.names.append(name or f"module{len(self.modules) - 1}")return Trueqw = QatWeight(importance, self.offload_q, self.round_dtype)qw._defer = Truetry:P.register_parametrization(module, "weight", qw)finally:qw._defer = Falseself.modules.append((module, module.parametrizations.weight[0]))self.names.append(name or f"module{len(self.modules) - 1}")return Truedef refresh(self) -> None:if not self.modules:returndef _refresh(item):module, qw = itemqw.refresh(module.parametrizations.weight.original)workers = min(self.max_workers, len(self.modules))if workers <= 1:for item in self.modules:_refresh(item)returnwith ThreadPoolExecutor(max_workers=workers) as ex:list(ex.map(_refresh, self.modules))def originals(self):return [m.parametrizations.weight.original for m, _ in self.modules]def weight_penalty(self, device: "torch.device | str | None" = None,fresh: bool = False) -> "torch.Tensor":"""Mean relative squared weight-space quant error ||W-Q(W)||^2/||W||^2.With ``fresh`` the penalty uses Q(W) of the *current* weights, so italways pulls W toward its own quantization lattice instead of a stalecached one."""total = Nonecount = 0for module, qw in self.modules:W = module.parametrizations.weight.originalq = qw.fresh_q(W) if fresh else qw.get_q(W)if q is None or q.shape != W.shape:continuedenom = W.pow(2).mean() + 1.0e-12165 unmodified linesreturn Nonedef _cache_get(reader, key: str):cache = getattr(reader, "_smq_qat_cache", None)if cache is None or key not in cache:return None, Falsereturn cache[key], Truedef _cache_set(reader, key: str, value) -> None:cache = getattr(reader, "_smq_qat_cache", None)if cache is None:cache = {}try:reader._smq_qat_cache = cacheexcept Exception: # noqa: BLE001 - reader without a __dict__: no cachingreturncache[key] = valuedef _tensors_by_name(reader) -> dict[str, Any]:cached, hit = _cache_get(reader, "tensors_by_name")if hit:return cachedout = {ti.name: ti for ti in reader.tensors}_cache_set(reader, "tensors_by_name", out)return outdef total_blocks(reader) -> int:37 unmodified lineskey_dim = state_size * group_count (q and k rows), value_dim = inner_size(v and z rows), head_v_dim = inner_size / time_step_rank."""cached, hit = _cache_get(reader, "ssm_dims")if hit:return cachedarch = _read_arch(reader)vals = (_meta_scalar(reader, f"{arch}.ssm.conv_kernel"),3 unmodified lines_meta_scalar(reader, f"{arch}.ssm.inner_size"),)if None in vals:_cache_set(reader, "ssm_dims", None)return Noneconv_kernel, state, group, tstep, inner = (int(v) for v in vals)if group <= 0 or tstep <= 0 or inner % tstep:raise ValueError(f"{arch}.ssm metadata inconsistent: inner_size={inner} time_step_rank={tstep}")out = {"conv_kernel": conv_kernel,"head_k_dim": state,"num_k_heads": group,2 unmodified lines"key_dim": state * group,"value_dim": inner,}_cache_set(reader, "ssm_dims", out)return outdef _layer_is_recurrent(reader, block: int) -> bool:288 unmodified linesloudly. NextN/MTP draft-head tensors ("blk.<N>.nextn.*") are skipped:llama.cpp never runs the draft layers."""key = f"specs:{block}"cached, hit = _cache_get(reader, key)if hit:return cachedarch = _read_arch(reader)ssm = _ssm_dims(reader)prefix = f"blk.{block}."5 unmodified linesif suffix.startswith("nextn."):continuespecs.append(_build_spec(ti.name, suffix, smqc.tensor_ggml_shape(ti), arch, ssm))_cache_set(reader, key, specs)return specs60 unmodified lines"output_norm.weight", ["norm.weight"],lambda a: [a], lambda h: h[0], "aux")return out_GGUF_CTX = Nonedef _gguf_ctx():"""Cached ``smqc.load_gguf()`` result (imports are otherwise repeated)."""global _GGUF_CTXif _GGUF_CTX is None:_GGUF_CTX = smqc.load_gguf()return _GGUF_CTXdef _gguf_f32(reader, name: str) -> np.ndarray:"""Dequantized f32 numpy view of one GGUF tensor (physical shape)."""_gguf, _reader_cls, dequantize_fn, *_rest = _gguf_ctx()return smqc.load_tensor_f32(_tensors_by_name(reader)[name], dequantize_fn)592 unmodified lines@torch.no_grad()def _forward_pre_norm(model, x: "torch.Tensor", autocast_dtype,use_autocast: bool = True) -> "torch.Tensor":"""Raw output of the (single) decoder layer, before the model's final norm."""holder = {}3 unmodified lineslayer = _get_decoder_layers(model)[0]h = layer.register_forward_hook(hook)try:ctx = torch.autocast(device_type=x.device.type, dtype=autocast_dtype, enabled=use_autocast)with ctx:model(inputs_embeds=x, use_cache=False)finally:24 unmodified linesdtype,micro_batch: int,out_mmap: Path | None = None,out_dtype: "torch.dtype | None" = None,) -> "_ActivationBuffer":if out_dtype is None:out_dtype = torch.bfloat16n = h.shape[0]buf: _ActivationBuffer | None = Nonefor r0 in range(0, n, micro_batch):r1 = min(n, r0 + micro_batch)x = h[r0:r1].to(device=device, dtype=dtype)y = fn(x).to(dtype=out_dtype).cpu()if buf is None:buf = _ActivationBuffer((n, *y.shape[1:]), mmap_path=out_mmap, dtype=out_dtype)buf[r0:r1] = yassert buf is not Nonebuf.flush()155 unmodified linesadaptive_step: bool = False,adaptive_rel: float = 0.05,micro_batch: int = 4,grad_accum: int = 4,requant_every: int = 10,norm_lr_multiplier: float = 10.0,warmup_frac: float = 0.05,fp16_round: bool = True,fresh_penalty: bool = False,train_types: set[str] | None = None,excluded_types: set[str] | None = None,grad_checkpointing: bool = True,propagate: str = "qat",offload_threshold: int = 64,offload_q="auto",seed: int = 0,verbose: bool = False,log=print,):self.reader = reader9 unmodified linesself.adaptive_step = adaptive_stepself.adaptive_rel = adaptive_relself.micro_batch = micro_batchself.grad_accum = max(1, int(grad_accum))self.requant_every = requant_everyself.norm_lr_multiplier = norm_lr_multiplierself.warmup_frac = max(0.0, float(warmup_frac))self.round_dtype = torch.float16 if (fp16_round and torch is not None) else Noneself.fresh_penalty = fresh_penaltyself.seed = int(seed)self.verbose = verboseself.train_types = train_typesself.excluded_types = excluded_types or set()self.grad_checkpointing = grad_checkpointing3 unmodified lines# estimated VRAM need would not fit; True/False force it.self.offload_q = offload_qself._offload_q_now = Falseself._eval_idx: list[int] = []self.log = logself.autocast_dtype = torch.bfloat16self.trained_dir = self.work_dir / "trained"29 unmodified linesreturn targetsdef _attached(self, model, block: int):manager = QatManager(offload_q=self._offload_q_now, round_dtype=self.round_dtype)layer = _get_decoder_layers(model)[0]for gguf_name, hf_name in self._trainable(block):try:2 unmodified linescontinueif not isinstance(module, nn.Linear):continueif manager.attach(module, self._importance(gguf_name, hf_name), name=hf_name):if self.verbose:self.log(f"blk.{block}: train {hf_name} <- {gguf_name}")return managerdef _collect_norm_params(self, model, block: int) -> list["nn.Parameter"]:62 unmodified linespassif h is None:raise RuntimeError("internal: block 0 activations must be built before train_block")# Hold out the tail of the corpus for adaptive-stop / eval decisions so# the stopping criterion is not measured on the sequences being fit.n_seq = h.shape[0]n_eval = min(8, max(1, n_seq // 4))self._eval_idx = list(range(n_seq - n_eval, n_seq)) if n_seq >= 2 * n_eval else list(range(n_seq))use_mmap = self._use_mmap(h.shape[0])targets_mmap = self.work_dir / f"tmp_targets_blk{block}.bin" if use_mmap else Noneout_mmap = self.work_dir / f"tmp_act_blk{block + 1}.bin" if use_mmap else None# 1. Full-precision targets: the raw (pre-norm) block output, so the# trained block reproduces exactly what is chained into the next one.# Run without autocast and keep fp32 so the target itself is exact.self.log(f"blk.{block}: computing full-precision targets ({h.shape[0]} seqs)")targets = _batched_forward(lambda x: _forward_pre_norm(model, x, self.autocast_dtype, use_autocast=False),h,self.device,torch.float32,self.micro_batch,out_mmap=targets_mmap,out_dtype=torch.float32,)gc.collect()if torch.cuda.is_available():23 unmodified lines) from eself._save(model, manager, norm_params, block, saved)# 2. Propagate corpus activations through the (fake-quantized) block.# "full" really does mean full precision: bypass the parametrization# so the next block sees the trained fp weights, not a stale cache.self.log(f"blk.{block}: propagating activations ({self.propagate})")full_propagation = self.propagate == "full"if manager.modules:if full_propagation:for _, qw in manager.modules:qw._defer = Trueelse:manager.refresh()self._log_weight_rmse(block, manager, "after final re-quantization (trained W vs Q(W))")model.eval()if manager.modules:label = ("FINAL, full precision" if full_propagationelse "FINAL, trained + re-quantized")self._log_eval(block, model, h, targets, label)out = _batched_forward(lambda x: _forward_pre_norm(model, x, self.autocast_dtype),h,14 unmodified linestorch.cuda.empty_cache()return outdef _eval_block(self, model, h, targets, indices=None, k: int = 8):"""(rmse, rel, cosine) of the block output vs the targets.By default this uses the held-out tail sequences (``self._eval_idx``)recorded when the block started, not the sequences being trained on."""if indices is None:indices = self._eval_idx or list(range(min(k, h.shape[0])))indices = list(indices)if not indices:return 0.0, 0.0, 0.0micro = max(1, min(self.micro_batch, len(indices)))se = ys = cos_sum = 0.0cnt = ncos = 0with torch.no_grad():for r0 in range(0, len(indices), micro):idx = indices[r0:r0 + micro]x = h[idx].to(device=self.device, dtype=torch.float32)y = targets[idx].to(device=self.device, dtype=torch.float32)pred = _forward_pre_norm(model, x, self.autocast_dtype).float()7 unmodified linesdef _log_eval(self, block: int, model, h, targets, label: str) -> None:rmse, rel, cos = self._eval_block(model, h, targets)self.log(f"blk.{block}: block-output error {label}: out_rmse={rmse:.3e} "f"(rel {100 * rel:.2f}%) cos={cos:.5f} [held-out seqs]")def _log_weight_rmse(self, block: int, manager, label: str) -> None:if not manager.modules:12 unmodified linesp.requires_grad_(True)param_groups = [{"params": quant_params, "lr": self.lr, "weight_decay": self.weight_decay}]if norm_params:param_groups.append({"params": norm_params,"lr": self.lr * self.norm_lr_multiplier,"weight_decay": 0.0,})# fused (CUDA) or per-tensor AdamW: the default multi-tensor path needs a# full extra copy of the optimizer state as scratch inside step().opt = None4 unmodified linesopt = Noneif opt is None:opt = torch.optim.AdamW(param_groups, betas=(0.9, 0.95), foreach=False)warmup = int(round(self.warmup_frac * max(1, self.steps)))horizon = max(1, self.steps - warmup)def lr_lambda(s: int) -> float:if warmup and s < warmup:return (s + 1) / float(warmup)prog = min(1.0, max(0.0, (s - warmup) / float(horizon)))return 0.05 + 0.95 * 0.5 * (1.0 + math.cos(math.pi * prog))scheduler = torch.optim.lr_scheduler.LambdaLR(opt, lr_lambda)n = h.shape[0]micro = max(1, min(self.micro_batch, n))accum = max(1, self.grad_accum)batch = micro * accumeval_set = set(self._eval_idx)train_idx = [i for i in range(n) if i not in eval_set] or list(range(n))rng = random.Random(self.seed + block)order = list(train_idx)rng.shuffle(order)cursor = 0def next_batch(k: int) -> list[int]:"""Sample k indices without replacement, reshuffling each epoch."""nonlocal order, cursorout: list[int] = []while len(out) < k:if cursor >= len(order):rng.shuffle(order)cursor = 0take = order[cursor:cursor + (k - len(out))]cursor += len(take)out.extend(take)return outif manager.modules:tq = time.time()manager.refresh() # the same quantization the first forward would do lazily8 unmodified lines"at the final re-quantization (w_rmse below will drift upward). ""Use requant_every=N for in-loop re-quantization.")if accum > 1:self.log(f"blk.{block}: effective batch = {batch} sequences "f"({micro} x {accum} gradient-accumulation micro-batches)")space = _SpaceStop()if self.adaptive_step:hint = ("press space to stop early and keep the current weights"11 unmodified linestry:step = 0while self.adaptive_step or step < self.steps:step_idx = next_batch(batch)opt.zero_grad(set_to_none=True)pen_part = Noneif self.weight_rmse_lambda and manager.modules:# The cached Q(W) is refreshed every requant_every steps;# --fresh-penalty re-quantizes each step for exactness at a# much higher cost.pen = manager.weight_penalty(device=self.device, fresh=self.fresh_penalty).to(dtype=torch.float32)pen_part = self.weight_rmse_lambda * pen# Backprop the (batch-independent) penalty once, so the# micro-batch loop does not reuse its graph.if pen_part.requires_grad:pen_part.backward()else:pen_part = Nonese_sum = ys_sum = loss_sum = 0.0cnt = 0last_mse = last_cos = 0.0for g in range(accum):sub = step_idx[g * micro:(g + 1) * micro]x = h[sub].to(device=self.device, dtype=torch.float32)y = targets[sub].to(device=self.device, dtype=torch.float32)ctx = torch.autocast(device_type=self.device.type, dtype=self.autocast_dtype)with ctx:pred = _forward_layer_train(model, x)pred_f = pred.float()mse = F.mse_loss(pred_f, y)loss = msecos_part = Noneif self.cosine_lambda:cos_loss = (1.0 - F.cosine_similarity(pred_f, y, dim=-1)).mean()cos_part = self.cosine_lambda * cos_lossloss = loss + cos_part# Scale by the number of micro-batches so the accumulated# gradient is the mean over `batch`, not a sum.(loss / accum).backward()with torch.no_grad():se_sum += float((pred_f.detach() - y).pow(2).sum())ys_sum += float(y.pow(2).sum())cnt += y.numel()loss_sum += float(loss.detach())last_mse = float(mse.detach())last_cos = float(cos_part.detach()) if cos_part is not None else 0.0torch.nn.utils.clip_grad_norm_(all_params, 1.0)opt.step()scheduler.step()3 unmodified linesmanager.refresh()self.log(f"blk.{block}: step {step + 1}: re-quantized {len(manager.modules)} "f"tensors in {time.time() - tq:.0f}s")out_rmse = (se_sum / max(cnt, 1)) ** 0.5y_rms = (ys_sum / max(cnt, 1)) ** 0.5out_rel = out_rmse / max(y_rms, 1e-30)at_end = not self.adaptive_step and step + 1 == self.stepsif (step + 1) % log_every == 0 or at_end:with torch.no_grad():w_rmse, w_rel, _rows = manager.weight_rmse()terms = f"mse {last_mse:.2e}"if self.cosine_lambda:terms += f" + cos {last_cos:.2e}"if pen_part is not None:terms += f" + wpen {float(pen_part.detach()):.2e}"logged_loss = loss_sum / accum + (float(pen_part.detach()) if pen_part is not None else 0.0)total = "" if self.adaptive_step else f"/{self.steps}"self.log(f"blk.{block}: step {step + 1}{total} loss={logged_loss:.6e} "f"[{terms}] out_rmse={out_rmse:.3e} (rel {100 * out_rel:.1f}%) "f"w_rmse={w_rmse:.3e} (rel {100 * w_rel:.2f}%) "f"lr={scheduler.get_last_lr()[0]:.2e} ({(time.time() - t0) / (step + 1):.2f}s/step)"3 unmodified lines"keeping the current weights")breakif self.adaptive_step and out_rel < self.adaptive_rel:# Confirm the minibatch estimate on the held-out set before# ending the block early.was_training = model.trainingmodel.eval()try:118 unmodified linesreturn indexdef _load_trained(path: Path | None, key: str, handles: dict | None = None):"""One trained tensor as float32 numpy (None if not trained).``handles`` keeps one ``safe_open`` per block file alive across the exportinstead of reopening the same file for every tensor."""if path is None:return Nonefrom safetensors import safe_openif handles is not None:f = handles.get(path)if f is None:f = safe_open(str(path), framework="pt")handles[path] = ftry:return f.get_tensor(key).to(torch.float32).cpu().numpy()except Exception: # noqa: BLE001 - missing keyreturn Nonetry:with safe_open(str(path), framework="np") as f:return np.asarray(f.get_tensor(key), dtype=np.float32)39 unmodified lines"""import gguf_gguf_py, _reader_cls, _dequant, _wr, _qt, GGUFValueType, _end = _gguf_ctx()index = _index_trained(trained_dir)if not index:7 unmodified linesspec_by_gname[spec.gguf] = specmodel_specs = _model_level_specs(reader)checks: dict[str, np.ndarray] = {}handles: dict = {} # path -> open safe_open, reused across tensorstry:for ti in reader.tensors:spec = model_specs.get(ti.name) or spec_by_gname.get(ti.name)arr = Noneblk = _block_of(ti.name)if spec is not None and blk is not None:vals = [_load_trained(index.get((blk, h)), h, handles) for h in spec.hf]if all(v is not None for v in vals):arr = spec.forward(vals)if arr is None:smqc.add_tensor_passthrough(writer, ti, reader)continueshape = smqc.tensor_ggml_shape(ti)if len(shape) == 1:writer.add_tensor(ti.name, np.ascontiguousarray(arr.reshape(-1), dtype=np.float32))else:# physical layout: rows = ne[1] (output), cols = ne[0] (input).# gguf-py takes the numpy array as-is and REVERSES its shape to get# ne, so the (ne[1], ne[0]) array is passed unchanged (never .T).# float16 maps to GGML F16 in gguf-py.if arr.shape[0] != shape[1] or arr.shape[1] != shape[0]:raise ValueError(f"trained tensor {ti.name!r} shape {arr.shape} does not "f"match GGUF ne={shape}")arr16 = np.ascontiguousarray(arr, dtype=np.float16)writer.add_tensor(ti.name, arr16)if len(checks) < 6:checks[ti.name] = np.array(arr16[:64, :64])written += 1finally:for f in handles.values():try:f.__exit__(None, None, None)except Exception: # noqa: BLE001 - best-effort closepass_copy_metadata_f16(reader, writer, GGUFValueType)writer.write_header_to_file()writer.write_kv_data_to_file()8 unmodified lines"""Re-open the written GGUF: every tensor must keep its source shape, and afew trained tensors must read back bit-exactly (catches transposed layouts,including square matrices whose shape alone would look right)."""_g, reader_cls, *_rest = _gguf_ctx()out = reader_cls(str(output))src = {t.name: tuple(int(x) for x in smqc.tensor_ggml_shape(t)) for t in reader.tensors}bad = []59 unmodified linesdef _disk_problems(reader, output: Path, work_dir: Path, lo: int, hi: int,tmp_dir=None, num_seqs: int = 0, seq_len: int = 0,offload_threshold: int = 0) -> list[str]:"""Fail BEFORE hours of training if the disks cannot hold trained + exported data."""gib = 2 ** 30trained, export = _export_plan(reader, lo, hi)4 unmodified linesitems = [("trained weights (fp32)", work_dir, trained),("export spool file", tmp, export),("exported GGUF", Path(output).resolve().parent, export)]# With mmap activations, one block needs its fp32 targets plus the bf16# input and output buffers on disk at the same time (4 + 2 + 2 B / element).if num_seqs and seq_len and offload_threshold > 0 and num_seqs > offload_threshold:try:hidden = int(smqc.tensor_ggml_shape(_tensors_by_name(reader)["token_embd.weight"])[0])except Exception: # noqa: BLE001 - no embedding metadata: skip the estimatehidden = 0if hidden:items.append(("activation mmap temps (targets + in/out)", work_dir,num_seqs * seq_len * hidden * 8))def existing(path) -> Path:pth = Path(path).resolve()54 unmodified linesadaptive_step: bool = False,adaptive_rel: float = 0.05,micro_batch: int = 4,grad_accum: int = 4,requant_every: int = 10,norm_lr_multiplier: float = 10.0,warmup_frac: float = 0.05,fp16_round: bool = True,fresh_penalty: bool = False,train_types: set[str] | None = None,tensor_type: list[tuple[str, str]] | None = None,grad_checkpointing: bool = True,6 unmodified linesdevice: str = "cuda",validate: bool = True,offload_q="auto",offload_threshold: int = 64,verbose: bool = False,) -> int:"""Block-wise QAT against SMQ's real Q2_K quantizer.1 unmodified line``adaptive_step`` continues each block with no step limit until theblock-output relative error is below ``adaptive_rel`` (0.05 = 5%) or space ispressed; ``steps`` is then only the cosine LR schedule horizon. Without theflag, ``steps`` remains the fixed number of optimizer steps per block.``requant_every`` re-runs the real Q2_K quantizer every N optimizer steps(default 10); a value of 0 freezes the fake-quant at the initial weights sothe forward no longer tracks training. ``grad_accum`` averages severalmicro-batches per optimizer step, ``warmup_frac`` warms up the LR, and``fp16_round`` fake-quants the fp16-rounded weights the export will contain.The weight-space penalty uses the cached Q(W) (refreshed every``requant_every`` steps); ``fresh_penalty`` re-quantizes every step instead,which is exact but much slower. Returns the trained-tensor count from theexport."""gguf_path = Path(gguf_path)output = Path(output)log = print_gguf_py, reader_cls, _deq, *_rest = _gguf_ctx()reader = reader_cls(str(gguf_path))arch = _read_arch(reader)n_blocks = total_blocks(reader)8 unmodified lines# the (slow) corpus load and before any training starts.problems += preflight(reader, (lo, hi), log=log)_wd = Path(work_dir) if work_dir else output.parent / (output.stem + ".qat_work")problems += _disk_problems(reader, output, _wd, lo, hi,num_seqs=num_seqs, seq_len=seq_len, offload_threshold=offload_threshold)_raise_if_problems(problems)if not torch.cuda.is_available() and device.startswith("cuda"):raise RuntimeError("CUDA requested but not available; use --device cpu")35 unmodified linesadaptive_step=adaptive_step,adaptive_rel=adaptive_rel,micro_batch=micro_batch,grad_accum=grad_accum,requant_every=requant_every,norm_lr_multiplier=norm_lr_multiplier,warmup_frac=warmup_frac,fp16_round=fp16_round,fresh_penalty=fresh_penalty,train_types=train_types,excluded_types=excluded,grad_checkpointing=grad_checkpointing,propagate=propagate,offload_q=offload_q,offload_threshold=offload_threshold,seed=seed,verbose=verbose,log=log,)h: _ActivationBuffer | None = None2 unmodified lineshf_dir = work_dir / f"hf_blk{b}"prepare_hf_partial(reader, hf_dir, b, log=log)if h is None:# Block 0 (or a mid-model start): embed the corpus directly from the# GGUF's own embedding table. Loading the whole partial model here# was wrong for a mid-model start (the embedding is not written for# lo > 0) and wasted VRAM on the block weights.emb = torch.from_numpy(_gguf_f32(reader, "token_embd.weight"))emb_mmap = work_dir / f"tmp_act_blk{b}.bin" if trainer._use_mmap(seqs.shape[0]) else Nonewith torch.no_grad():for r0 in range(0, seqs.shape[0], micro_batch):r1 = min(seqs.shape[0], r0 + micro_batch)batch_h = emb[seqs[r0:r1]].to(dtype=torch.bfloat16)if h is None:h = _ActivationBuffer((seqs.shape[0], *batch_h.shape[1:]), mmap_path=emb_mmap)h[r0:r1] = batch_hassert h is not Noneh.flush()log(f"blk.{b}: embedded corpus -> {h.shape} (mmap={emb_mmap is not None})")del embgc.collect()h = trainer.train_block(b, h, hf_dir)log(f"blk.{b}: done in {time.time() - t0:.0f}s")if not keep_block_dirs:30 unmodified linesap.add_argument("--tmp-dir", type=Path,help="where the export spools tensor data (default: TMPDIR or next to --output)")args = ap.parse_args()_g, _rc, *_r = _gguf_ctx()_reader = _rc(str(args.gguf))if args.export_trained:if not args.output:
107 unmodified lines10810911011111211311411511663 unmodified lines1801811821831841851864 unmodified lines191192193194195196107 unmodified lines"is no step limit, so press space to stop a block and keep its weights")t.add_argument("--adaptive-rel", type=float, default=0.05,help="block-output relative-error target for --adaptive-step (0.05 = 5%%)")t.add_argument("--micro-batch", type=int, default=4)t.add_argument("--requant-every", type=int, default=0,help="re-run the real quantizer every N steps (0 = once per block)")t.add_argument("--train-types", default=None,help="comma-separated tensor types to train (default: all quantized)")t.add_argument("--no-grad-checkpointing", action="store_true")63 unmodified linesadaptive_step=args.adaptive_step,adaptive_rel=args.adaptive_rel,micro_batch=args.micro_batch,requant_every=args.requant_every,train_types=train_types,tensor_type=tensor_type,grad_checkpointing=not args.no_grad_checkpointing,4 unmodified linesimatrix=args.imatrix,tokenizer=args.tokenizer,device=device,)107 unmodified lines10810911011111211311411511611711811912012112212312412512612712812913013163 unmodified lines1951961971981992002012022032042052064 unmodified lines211212213214215216217107 unmodified lines"is no step limit, so press space to stop a block and keep its weights")t.add_argument("--adaptive-rel", type=float, default=0.05,help="block-output relative-error target for --adaptive-step (0.05 = 5%%)")t.add_argument("--micro-batch", type=int, default=4,help="sequences per forward/backward micro-batch")t.add_argument("--grad-accum", type=int, default=4,help="gradient-accumulation micro-batches per optimizer step ""(effective batch = micro_batch * grad_accum)")t.add_argument("--requant-every", type=int, default=10,help="re-run the real quantizer every N steps (0 = once per block; ""0 makes the forward independent of the weight updates)")t.add_argument("--norm-lr-mult", type=float, default=10.0,help="learning-rate multiplier for 1-D norm parameters")t.add_argument("--warmup-frac", type=float, default=0.05,help="fraction of steps used for the linear LR warmup")t.add_argument("--no-fp16-round", action="store_true",help="fake-quant the fp32 weights directly instead of first rounding ""to the fp16 storage the exported GGUF uses")t.add_argument("--fresh-penalty", action="store_true",help="re-quantize every step for the weight-space penalty instead of ""reusing the cache refreshed every --requant-every steps (much slower)")t.add_argument("--train-types", default=None,help="comma-separated tensor types to train (default: all quantized)")t.add_argument("--no-grad-checkpointing", action="store_true")63 unmodified linesadaptive_step=args.adaptive_step,adaptive_rel=args.adaptive_rel,micro_batch=args.micro_batch,grad_accum=args.grad_accum,requant_every=args.requant_every,norm_lr_multiplier=args.norm_lr_mult,warmup_frac=args.warmup_frac,fp16_round=not args.no_fp16_round,fresh_penalty=args.fresh_penalty,train_types=train_types,tensor_type=tensor_type,grad_checkpointing=not args.no_grad_checkpointing,4 unmodified linesimatrix=args.imatrix,tokenizer=args.tokenizer,device=device,verbose=args.verbose,)
smq_qat.py+425-129
train_smq_qat.py+24-3