""" Export a Hugging Face Llama 3.x checkpoint (model.safetensors + config.json) to the llama3.c int8 (version 2) format, using only numpy (no torch / safetensors needed). python3 export_hf_q8.py /path/to/Llama-3.2-1B-Instruct llama32_1b_instruct_q80.bin Header extension (inside the 256-byte v2 header, after group_size, all little-endian): float rope_theta, float rope_factor, float low_freq_factor, float high_freq_factor, int original_max_position_embeddings (factor == 0 means "no llama3 rope scaling") int arch (0 = llama3, 1 = qwen2), float norm_eps, int qkv_bias, int special_start (first special token id), int bos_id, int eos_id int q4_mask: bit k set = matrix kind k (0 wq, 1 wk, 2 wv, 3 wo, 4 w1, 5 w2, 6 w3) is stored as Q4 int head_dim, n_experts, n_active, moe_hidden, qk_norm, norm_topk (Qwen3 / Qwen3-MoE; 0 = n/a) int q4_format: 1 = asymmetric groups of 32 with fp16 scale + min (0 / absent: the old symmetric Q4) fp32 section: attention norms, ffn norms, final norm, [qkv biases], [q_norm (L, head_dim), k_norm (L, head_dim)] MoE layers: router wg (L, n_experts, dim) in Q8 after wo; w1/w3 (L, n_experts * moe_hidden, dim) and w2 (L, n_experts * dim, moe_hidden), every expert a contiguous block of rows. If qkv_bias, the fp32 section continues after the final norm with bq (L, dim), bk (L, kv_dim), bv (L, kv_dim). Q8 tensors: int8 values, then fp32 scales per `gs` values. Q4 tensors (q4_format 1): groups of 32 values u in 0..15 packed in 16 bytes (byte k = u[k] in the low nibble, u[k+16] in the high nibble), then per group [s, m] as two fp16 (value = s * u + m). Embedding / classifier are always Q8. python3 export_hf_q8.py [gs] [--q4 [kinds]] kinds e.g. wq,wk,wo,w1,w3 (default all) Supported: LlamaForCausalLM (Llama 3.x), Qwen2ForCausalLM (Qwen2.5), Qwen3ForCausalLM, Qwen3MoeForCausalLM. """ import json import os import struct import sys import numpy as np def load_safetensors(path): """returns {name: np.ndarray(float32)} lazily converted from bf16/f16/f32""" with open(path, "rb") as f: n = struct.unpack(" 1e-30, scale, 0.0).astype(np.float32) # all-(near-)zero groups: avoid 1/denormal inv = np.where(scale > 0, 1.0 / np.where(scale > 0, scale, 1.0), 0.0).astype(np.float32) q = np.round(g * inv[:, None]).astype(np.int8) err = np.abs(q.astype(np.float32) * scale[:, None] - g).max() return q, scale.astype(np.float32), err KINDS = ["wq", "wk", "wv", "wo", "w1", "w2", "w3"] def quantize_q4(w, gs=32, imp=None): """asymmetric 4-bit per group of 32: value = s * u + m, u in 0..15, s and m in fp16. For every group, candidate grids are tried (scale (15 + d) / (max - min), d in -1..1 step 0.1) and for each the integers are fixed and (s, m) solved by weighted least squares; the best fit wins. Weights: importance of the input channel (mean x^2 on calibration text) if given, otherwise |w| + rms(group) (larger weights matter more, as in llama.cpp's k-quants). Returns packed nibbles (byte k = u[k] | u[k+16] << 4) and per group [s, m] as fp16 pairs.""" rows, cols = w.reshape(-1, w.shape[-1]).shape g = w.astype(np.float32).reshape(-1, gs) if imp is None: wt = np.abs(g) + np.sqrt((g * g).mean(axis=1, keepdims=True)) else: # (cols,) or, for stacked MoE experts, (n_experts, cols): one row per block of rows imp = np.asarray(imp, np.float32).reshape(-1, cols) imp = imp / max(float(imp.mean()), 1e-30) per = rows // imp.shape[0] wt = np.repeat(imp, per, axis=0).reshape(rows, cols // gs, gs).reshape(-1, gs) wt = wt * (np.abs(g) + np.sqrt((g * g).mean(axis=1, keepdims=True))) wt = wt + 1e-12 gmin, gmax = g.min(axis=1), g.max(axis=1) rng = np.maximum(gmax - gmin, 1e-30) sw = wt.sum(axis=1) sx = (wt * g).sum(axis=1) best_err = np.full(len(g), np.inf, np.float32) best_s = rng / 15.0 best_m = gmin.copy() for d in np.arange(-1.0, 1.0001, 0.1): iscale = (15.0 + d) / rng u = np.clip(np.round((g - gmin[:, None]) * iscale[:, None]), 0, 15) sl = (wt * u).sum(axis=1) sll = (wt * u * u).sum(axis=1) slx = (wt * u * g).sum(axis=1) D = sw * sll - sl * sl ok = D > 1e-30 Ds = np.where(ok, D, 1.0) s_ = np.where(ok, (sw * slx - sl * sx) / Ds, rng / 15.0) m_ = np.where(ok, (sll * sx - sl * slx) / Ds, gmin) # the integers for the fitted (s, m), then the error inv = np.where(np.abs(s_) > 1e-30, 1.0 / np.where(np.abs(s_) > 1e-30, s_, 1.0), 0.0) u2 = np.clip(np.round((g - m_[:, None]) * inv[:, None]), 0, 15) err = (wt * (u2 * s_[:, None] + m_[:, None] - g) ** 2).sum(axis=1) better = err < best_err best_err[better] = err[better] best_s[better] = s_[better] best_m[better] = m_[better] s16 = best_s.astype(np.float16) m16 = best_m.astype(np.float16) sf, mf = s16.astype(np.float32), m16.astype(np.float32) # integers for the stored (fp16) values inv = np.where(np.abs(sf) > 1e-30, 1.0 / np.where(np.abs(sf) > 1e-30, sf, 1.0), 0.0) u = np.clip(np.round((g - mf[:, None]) * inv[:, None]), 0, 15).astype(np.uint8) packed = (u[:, :16] | (u[:, 16:] << 4)).astype(np.uint8) err = np.abs(u.astype(np.float32) * sf[:, None] + mf[:, None] - g).max() sm = np.stack([s16, m16], axis=1) # (groups, 2) fp16 return packed, sm, err INPUT_OF = {"wq": "att_in", "wk": "att_in", "wv": "att_in", "wo": "wo_in", "w1": "ffn_in", "w3": "ffn_in", "w2": "w2_in"} _JOB = {} def load_imatrix(path): """per-layer input-channel importance (mean x^2 on calibration text): a .imx file written by `runq -m imatrix -i data/calibration.txt -o stats.imx`, or an .npz from calibrate.py. MoE: ffn_in / w2_in are (n_experts, channels), one row per expert; experts that saw no calibration token get the mean over the other experts of the layer.""" if not path.endswith(".imx"): z = np.load(path) return {k: z[k] for k in z.files} raw = open(path, "rb").read() magic, L, dim, q_dim, H, E, mh = struct.unpack_from("<7i", raw, 0) assert magic == 0x31584D4E, "not an imatrix file" off = 7 * 4 + 8 EE = max(E, 1) def take(n): nonlocal off a = np.frombuffer(raw, np.float32, n, off).copy() off += 4 * n return a att = take(L * dim).reshape(L, dim) wo = take(L * q_dim).reshape(L, q_dim) ffn = take(L * EE * dim).reshape(L, EE, dim) w2 = take(L * EE * H).reshape(L, EE, H) out = {} for l in range(L): out[f"att_in.{l}.sq"] = att[l] out[f"wo_in.{l}.sq"] = wo[l] if E > 0: cnt = np.frombuffer(raw, np.int64, L * E, off).reshape(L, E)[l] for a in (ffn, w2): seen = cnt > 0 if seen.any() and not seen.all(): a[l][~seen] = a[l][seen].mean(axis=0) out[f"ffn_in.{l}.sq"] = ffn[l] out[f"w2_in.{l}.sq"] = w2[l] else: out[f"ffn_in.{l}.sq"] = ffn[l, 0] out[f"w2_in.{l}.sq"] = w2[l, 0] return out def _quant_job(key): kind, l = key w = _JOB["get"][kind](l) if kind in _JOB["q4"] and kind != "wg": imp = _JOB["imp"].get(f"{INPUT_OF[kind]}.{l}.sq") if _JOB["imp"] else None q, sc, err = quantize_q4(w, imp=imp) else: q, sc, err = quantize_q80(w, _JOB["gs"]) return q.tobytes() + sc.tobytes(), float(err) KINDS_HYB = KINDS + ["li", "lo"] # + linear-attention input (qkv|z|b|a) and output projections def _hyb_job(key): kind, l = key w = _JOB["get"][kind](l) if kind in _JOB["q4"]: imp = _JOB["imp"].get(f"{_JOB['inp'][kind]}.{l}.sq") if _JOB["imp"] else None if imp is not None: # statistics rows can be wider (wo / out_proj share one width) imp = np.asarray(imp)[: w.shape[-1]] q, sc, err = quantize_q4(w, imp=imp) else: q, sc, err = quantize_q80(w, _JOB["gs"]) return q.tobytes() + sc.tobytes(), float(err) def export_qwen35(cfg_all, T, out_path, q4_kinds, stats, gs): """Qwen3.5 / Qwen3.8 dense text model (model_type qwen3_5), arch 3. Hybrid layers: Gated DeltaNet linear attention, every `full_attention_interval`-th layer gated full attention with partial RoPE. Layout after the 256-byte header (which adds int hybrid[8] = full_interval, linear k heads, linear v heads, k head dim, v head dim, conv kernel, attention output gate, rotary dims): fp32: att norms (L, dim), ffn norms (L, dim), final norm, q_norm / k_norm (Lf, head_dim) of the full layers, then for the linear layers conv (Ll, conv_dim, K), dt_bias (Ll, nv), A = -exp(A_log) (Ll, nv), gated-norm weight (Ll, dv). All zero-centered RMSNorm weights are stored as 1 + w. Quantized: embedding; full layers wq (q rows), wgate, wk, wv, wo; linear layers w_in = [qkv | z | b | a] rows, w_out; every layer w1, w2, w3; classifier. Vision tower and MTP head are not exported.""" cfg = cfg_all.get("text_config", cfg_all) P = "model.language_model." if "model.language_model.embed_tokens.weight" in T else "model." dim, hidden, L = cfg["hidden_size"], cfg["intermediate_size"], cfg["num_hidden_layers"] nh, nkv, hd = cfg["num_attention_heads"], cfg["num_key_value_heads"], cfg["head_dim"] vocab, eps = cfg["vocab_size"], float(cfg["rms_norm_eps"]) rp = cfg.get("rope_parameters", {}) theta = float(rp.get("rope_theta", cfg.get("rope_theta", 10000.0))) rot = int(hd * rp.get("partial_rotary_factor", cfg.get("partial_rotary_factor", 1.0))) nk, nv = cfg["linear_num_key_heads"], cfg["linear_num_value_heads"] dk, dv, K = cfg["linear_key_head_dim"], cfg["linear_value_head_dim"], cfg["linear_conv_kernel_dim"] types = cfg["layer_types"] interval = cfg.get("full_attention_interval", 4) assert all((t == "full_attention") == ((l + 1) % interval == 0) for l, t in enumerate(types)), "irregular layer types" full = [l for l in range(L) if types[l] == "full_attention"] lin = [l for l in range(L) if types[l] != "full_attention"] gate = int(cfg.get("attn_output_gate", True)) seq_len = min(int(cfg.get("max_position_embeddings", 262144)), 262144) g = lambda n: T[P + n].astype(np.float32) lay = lambda l, n: T[f"{P}layers.{l}.{n}"].astype(np.float32) eos = 248046 if vocab > 200000 else cfg.get("eos_token_id", 0) bos = cfg.get("bos_token_id") or 248044 special_start = 248044 q4_mask = sum(1 << KINDS_HYB.index(k) for k in q4_kinds) out = open(out_path, "wb") out.write(struct.pack("