"""Remove (or mask, or permute) whole experts in a GGUF and write a new GGUF. Architecture section 6.1. python3 slicer.py --src native.gguf --keep keeplists/c-reap-96.json --mode slice|mask --out c-reap-96.gguf python3 slicer.py --src native.gguf --rand 96 --seed 0 [--mode slice --out rand-96.gguf] # writes keeplists/rand-96.json python3 slicer.py --src native.gguf --permute SEED --out perm.gguf # test only python3 slicer.py --list native.gguf # print the tensor table Tensor classification of native.gguf (Inkling-2-Mini UD-Q8_K_XL, arch inkling2_loop, 744 tensors), read from the tensor table for blk.0, blk.6 and blk.20 (ggml shapes; types F32=0, BF16=30, NVFP4=40): expert-indexed (expert axis = last ggml axis = numpy axis 0): blk.N.ffn_gate_up_exps.weight [2304, 2304, 128] NVFP4 in layers 0-19, BF16 in layers 20-23 blk.N.ffn_down_exps.weight [1152, 2304, 128] NVFP4 in layers 0-19, BF16 in layers 20-23 blk.N.ffn_gate_up_exps.scale [128] F32, layers 0-19 only (per-expert NVFP4 weight scale) blk.N.ffn_down_exps.scale [128] F32, layers 0-19 only blk.N.ffn_gate_inp.weight [2304, 128] F32, router blk.N.exp_probs_b.bias [128] F32, selection bias (separate tensor, so mask mode is possible) not expert-indexed but has a 128 axis: blk.N.attn_q_clip.weight [128, 24] F32, per-head q clip: 128 = head width, 24 = heads The loop tensors of blk.6-17 (loop_*_ctrl_*, loop_msg_query) have no 128 axis. Streaming: tensors are read through GGUFReader's memmap and written one at a time. """ import argparse import json import os import re import sys import numpy as np sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from gguf_tools import arch, expert_count_key, field, gguf, layer_of, to_f32 # noqa: E402 # Suffix after "blk.N." -> role. Every one has exactly one axis of length n_expert, which indexes experts. EXPERT_INDEXED = { 'ffn_gate_up_exps.weight': 'experts gate+up, fused [n_embd, 2*n_ff_exp, n_expert]', 'ffn_down_exps.weight': 'experts down, fused [n_ff_exp, n_embd, n_expert]', 'ffn_gate_up_exps.scale': 'per-expert weight scale of gate_up [n_expert]', 'ffn_down_exps.scale': 'per-expert weight scale of down [n_expert]', 'ffn_gate_inp.weight': 'router [n_embd, n_expert]', 'exp_probs_b.bias': 'selection bias [n_expert]', } BIAS = 'exp_probs_b.bias' # Suffix after "blk.N." -> why a length-n_expert axis there is not an expert index. NOT_EXPERT_INDEXED = { 'attn_q_clip.weight': 'per-head q clip [head_dim=128, n_head=24]; the 128 is the attention head width', } def suffix(name): m = re.match(r'blk\.\d+\.(.+)$', name) return m.group(1) if m else None def classify(t, n_expert): """-> (kind, ggml_axis_or_None, note). kind in expert | not | plain | UNCLASSIFIED.""" shape = [int(x) for x in t.shape] axes = [i for i, d in enumerate(shape) if d == n_expert] sfx = suffix(t.name) if sfx in EXPERT_INDEXED: if len(axes) != 1: raise SystemExit(f'{t.name}: expected exactly one axis of length {n_expert}, shape {shape}') return 'expert', axes[0], EXPERT_INDEXED[sfx] if len(axes) > 1 and sfx is not None: raise SystemExit(f'{t.name}: two axes of length {n_expert} ({shape}); settle with the permutation test') if not axes or sfx is None: return 'plain', None, '' if sfx in NOT_EXPERT_INDEXED: return 'not', None, NOT_EXPERT_INDEXED[sfx] return 'UNCLASSIFIED', axes[0], f'has an axis of length {n_expert} and is in neither list' def table(reader): n = field(reader, expert_count_key(reader)) rows = [] for t in reader.tensors: kind, ax, note = classify(t, n) rows.append({'name': t.name, 'type': t.tensor_type.name, 'shape': [int(x) for x in t.shape], 'bytes': int(t.n_bytes), 'class': kind, 'expert_axis': ax, 'note': note}) return n, rows def do_list(path): r = gguf.GGUFReader(path) n, rows = table(r) print(f'arch {arch(r)} {expert_count_key(r)} = {n}') for f in r.fields.values(): if 'expert' in f.name or f.name.endswith(('block_count', 'loop_start', 'loop_end', 'loop_count')): print(f' {f.name} = {f.contents()}') for x in rows: print(f"{x['name']:48s} {x['type']:6s} {str(x['shape']):24s} {x['bytes']:>12d} {x['class']:12s} {x['note']}") bad = [x['name'] for x in rows if x['class'] == 'UNCLASSIFIED'] print(f'tensors {len(rows)} expert-indexed {sum(x["class"] == "expert" for x in rows)} unclassified {len(bad)}') return bad def expert_layers(reader, n): return sorted({layer_of(x['name']) for x in table(reader)[1] if x['class'] == 'expert'}) def rand_keeplist(reader, k, seed, out_dir): n = field(reader, expert_count_key(reader)) rng = np.random.default_rng(seed) # one generator, one draw per layer in layer order layers = {str(l): sorted(int(e) for e in rng.choice(n, size=k, replace=False)) for l in expert_layers(reader, n)} kl = {'version': f'rand-{k}', 'K': k, 'mix': None, 'method': 'rand', 'seed': seed, 'layers': layers} os.makedirs(out_dir, exist_ok=True) path = os.path.join(out_dir, f'rand-{k}.json') with open(path, 'w') as fh: json.dump(kl, fh) print(f'wrote {path}') return kl def check_keeplist(kl, layers, n, variable=False): k = None if variable else int(kl['K']) # variable: per-layer counts (T5 mask only; expert_count stays n) for l in layers: ids = kl['layers'][str(l)] assert (variable or len(ids) == k) and ids == sorted(set(ids)) and 0 <= ids[0] and ids[-1] < n, f'bad keep list for layer {l}' return k def build(src, out, mode, keep=None, perm_seed=None): """mode: slice | mask | permute. keep: keep-list dict. Returns a summary dict.""" r = gguf.GGUFReader(src) n, rows = table(r) bad = [x['name'] for x in rows if x['class'] == 'UNCLASSIFIED'] if bad: raise SystemExit(f'refusing: {len(bad)} unclassified tensor(s) with a {n} axis: {bad[:8]}') layers = expert_layers(r, n) idx = {} # layer -> index array along the expert axis if mode == 'permute': rng = np.random.default_rng(perm_seed) # one permutation per layer, in layer order idx = {l: rng.permutation(n) for l in layers} k = n else: k = check_keeplist(keep, layers, n, variable=(mode == 'mask' and keep.get('K') is None)) idx = {l: np.asarray(keep['layers'][str(l)], dtype=np.int64) for l in layers} if mode == 'mask': for l in layers: assert any(x['name'] == f'blk.{l}.{BIAS}' for x in rows), f'mask mode needs blk.{l}.{BIAS}' ecount_key = expert_count_key(r) w = gguf.GGUFWriter(out, arch=arch(r), endianess=r.endianess) align = field(r, 'general.alignment') if align is not None: w.data_alignment = int(align) for f in r.fields.values(): if f.name == 'general.architecture' or f.name.startswith('GGUF.'): continue vt = f.types[0] st = f.types[-1] if vt == gguf.GGUFValueType.ARRAY else None val = f.contents() if f.name == ecount_key and mode == 'slice': val = k w.add_key_value(f.name, val, vt, sub_type=st) # plan: (tensor, output-type, numpy-shape, transform) plan, notes = [], [] for t, x in zip(r.tensors, rows): shape, ttype, fn = tuple(t.data.shape), t.tensor_type, None l = layer_of(t.name) if x['class'] == 'expert' and mode in ('slice', 'permute'): ax_ggml, ii = x['expert_axis'], idx[l] ax = len(shape) - 1 - ax_ggml if t.data.dtype == np.uint8: # raw bytes: block-quantised (or BF16) storage assert t.n_bytes % n == 0, f'{t.name}: bytes per expert do not divide evenly' if t.data.dtype == np.uint8 and ax_ggml == 0: # expert axis is the byte axis: only allowed for 1-element blocks (e.g. BF16) bs, ts = gguf.GGML_QUANT_SIZES[ttype] assert bs == 1 and shape[-1] == n * ts, f'{t.name}: expert axis inside a quant block' shape = shape[:-1] + (len(ii) * ts,) fn = (lambda d, ii=ii, ts=ts: np.ascontiguousarray( np.take(d.reshape(d.shape[:-1] + (n, ts)), ii, axis=-2)).reshape(d.shape[:-1] + (len(ii) * ts,))) else: assert shape[ax] == n, (t.name, shape, ax) shape = shape[:ax] + (len(ii),) + shape[ax + 1:] fn = (lambda d, ii=ii, ax=ax: np.ascontiguousarray(np.take(d, ii, axis=ax))) elif mode == 'mask' and suffix(t.name) == BIAS: removed = np.setdiff1d(np.arange(n), idx[l]) if ttype != gguf.GGMLQuantizationType.F32: notes.append(f'{t.name}: converted {ttype.name} -> F32 for mask') print(notes[-1]) ttype = gguf.GGMLQuantizationType.F32 def fn(d, t=t, removed=removed): b = to_f32(t).copy() b[removed] = -1e9 return b plan.append((t, ttype, shape, fn)) predicted = 0 for t, ttype, shape, fn in plan: if fn is None: nb = int(t.data.nbytes) w.add_tensor_info(t.name, t.data.shape, t.data.dtype, nb, raw_dtype=ttype) else: dt = np.float32 if (ttype == gguf.GGMLQuantizationType.F32 and t.tensor_type != ttype) else t.data.dtype nb = int(np.prod(shape)) * np.dtype(dt).itemsize w.add_tensor_info(t.name, shape, np.dtype(dt), nb, raw_dtype=ttype) predicted += nb w.write_header_to_file() w.write_kv_data_to_file() w.write_ti_data_to_file() for t, ttype, shape, fn in plan: d = t.data if fn is None else fn(t.data) assert tuple(d.shape) == tuple(shape), (t.name, d.shape, shape) w.write_tensor_data(d, tensor_endianess=r.endianess) w.close() # reopen and check o = gguf.GGUFReader(out) assert field(o, ecount_key) == (k if mode == 'slice' else n), 'expert_count wrong' got = {t.name: t for t in o.tensors} assert [t.name for t in o.tensors] == [t.name for t in r.tensors], 'tensor order changed' total = 0 for t, ttype, shape, fn in plan: u = got[t.name] assert u.tensor_type == ttype and tuple(u.data.shape) == tuple(shape), f'{t.name}: type/shape wrong' total += int(u.n_bytes) assert total == predicted, f'total bytes {total} != predicted {predicted}' # spot check: first and last kept expert of every sliced/permuted tensor are byte-identical spot = 0 for (t, ttype, shape, fn), x in zip(plan, rows): if x['class'] == 'expert' and mode in ('slice', 'permute'): if t.data.dtype == np.uint8 and x['expert_axis'] == 0: # small byte-axis tensor: compare whole assert fn(t.data).tobytes() == got[t.name].data.tobytes(), f'{t.name}: not byte-identical' spot += 1 continue ax = len(t.data.shape) - 1 - x['expert_axis'] ii = idx[layer_of(t.name)] for j in (0, len(ii) - 1): a = np.take(t.data, [ii[j]], axis=ax) b = np.take(got[t.name].data, [j], axis=ax) assert a.tobytes() == b.tobytes(), f'{t.name}: expert {ii[j]} not byte-identical' spot += 1 res = {'src': src, 'out': out, 'mode': mode, 'K': k, 'n_expert_src': n, 'layers': len(layers), 'tensor_bytes': total, 'file_bytes': os.path.getsize(out), 'src_file_bytes': os.path.getsize(src), 'spot_checks': spot, 'notes': notes} print(json.dumps(res)) return res def main(argv=None): p = argparse.ArgumentParser() p.add_argument('--list', metavar='GGUF') p.add_argument('--src') p.add_argument('--keep') p.add_argument('--rand', type=int) p.add_argument('--seed', type=int, default=0) p.add_argument('--keeplist-dir', default='/srv/prune/out/keeplists') p.add_argument('--mode', choices=['slice', 'mask'], default='slice') p.add_argument('--permute', type=int, metavar='SEED') p.add_argument('--out') a = p.parse_args(argv) if a.list: return 1 if do_list(a.list) else 0 if a.permute is not None: return build(a.src, a.out, 'permute', perm_seed=a.permute) and 0 if a.rand is not None: keep = rand_keeplist(gguf.GGUFReader(a.src), a.rand, a.seed, a.keeplist_dir) else: with open(a.keep) as fh: keep = json.load(fh) if a.out: build(a.src, a.out, a.mode, keep=keep) return 0 if __name__ == '__main__': sys.exit(main())