patrickbdevaney commited on
Commit
cd66abd
·
verified ·
1 Parent(s): 71dff29

MTP block is runnable: recurrent-state rollback + draft repack

Browse files
Files changed (1) hide show
  1. make_mtp_draft.py +203 -0
make_mtp_draft.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Repackage GLM-5.3's native MTP block (blk.45) as a standalone draft GGUF.
3
+
4
+ GLM-5.3 ships a Multi-Token Prediction module inside every GGUF: blk.45, with nextn.eh_proj /
5
+ enorm / hnorm / shared_head_norm plus a full MLA+DSA attention and a 144-expert MoE. Nothing
6
+ executes it - transformers drops it on load, llama.cpp loads it and leaves it out of the graph.
7
+ It is roughly 1.5 GiB of every quant that currently does no work.
8
+
9
+ This lifts it into a model llama.cpp can actually run as a speculative draft. The repackaging is
10
+ byte-preserving: quantised blocks are copied verbatim, never dequantised and requantised, so the
11
+ draft is exactly the tensor that shipped in the parent file.
12
+
13
+ Three renames carry the design:
14
+
15
+ blk.45.* -> blk.0.* the MTP block becomes the draft's only layer
16
+ blk.45.nextn.shared_head_norm -> output_norm it IS the final norm before the shared lm_head
17
+ (token_embd, output) -> copied MTP has no embedding or head of its own; the
18
+ reference shares the parent's, so the draft
19
+ must carry a copy to stand alone
20
+
21
+ The result is ~2.3 GiB at IQ3_M and pairs with exactly one parent quant. It is NOT interchangeable
22
+ across quants: hidden states drift hard between quantisations (IQ3_M vs IQ4_XS cosine 0.891
23
+ against a 0.999 same-quant floor), so a draft built from one parent must be served with that
24
+ parent.
25
+ """
26
+ import argparse, logging, os, sys
27
+ from pathlib import Path
28
+
29
+ # Prefer an installed gguf, so this script is usable by anyone who has `pip install gguf`, and fall
30
+ # back to a checkout beside this tree for the case where it is not installed. GGUF_PY_DIR overrides
31
+ # both, for a llama.cpp checked out somewhere else entirely.
32
+ try:
33
+ import gguf
34
+ except ImportError: # noqa: E722
35
+ _candidates = []
36
+ if os.environ.get("GGUF_PY_DIR"):
37
+ _candidates.append(Path(os.environ["GGUF_PY_DIR"]))
38
+ _here = Path(__file__).resolve()
39
+ _candidates += [
40
+ _here.parent.parent.parent / "glm5-llama.cpp" / "gguf-py",
41
+ _here.parent.parent.parent / "llama.cpp" / "gguf-py",
42
+ _here.parent.parent / "llama.cpp" / "gguf-py",
43
+ ]
44
+ for _c in _candidates:
45
+ if (_c / "gguf").is_dir():
46
+ sys.path.insert(0, str(_c))
47
+ break
48
+ else:
49
+ sys.exit("cannot find the gguf python package - `pip install gguf`, "
50
+ "or set GGUF_PY_DIR to a llama.cpp gguf-py directory")
51
+ import gguf # noqa: E402
52
+ from tqdm import tqdm # noqa: E402
53
+
54
+ logger = logging.getLogger("make_mtp_draft")
55
+
56
+ SRC_ARCH = "glm5-next"
57
+ DST_ARCH = "glm5-next-mtp"
58
+
59
+ # Keys that describe machinery the MTP block does not have. blk.45 carries no hc_* tensors (it is
60
+ # a plain pre-norm residual block, unlike the 45 hyper-connected layers ahead of it) and no ssm_*
61
+ # tensors (it is MLA, not KDA), so advertising either would make the loader look for weights that
62
+ # are not in the file.
63
+ DROP_SUFFIXES = (
64
+ ".attention.hc.mult", ".attention.hc.sinkhorn_iters", ".attention.hc.eps",
65
+ ".ssm.conv_kernel", ".ssm.gate_lower_bound", ".kda.head_dim",
66
+ ".nextn_predict_layers",
67
+ )
68
+
69
+
70
+ def main() -> None:
71
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
72
+ ap.add_argument("src", type=Path, help="parent GGUF containing blk.45")
73
+ ap.add_argument("dst", type=Path, help="draft GGUF to write")
74
+ ap.add_argument("--mtp-layer", type=int, default=None,
75
+ help="source block index of the MTP module (default: block_count-1)")
76
+ ap.add_argument("--force", action="store_true", help="overwrite dst if it exists")
77
+ ap.add_argument("--verbose", action="store_true")
78
+ args = ap.parse_args()
79
+ logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO,
80
+ format="%(levelname)s: %(message)s")
81
+
82
+ if args.dst.exists() and not args.force:
83
+ logger.error("%s exists; pass --force to overwrite", args.dst)
84
+ sys.exit(1)
85
+
86
+ reader = gguf.GGUFReader(args.src, "r")
87
+
88
+ arch_f = reader.get_field("general.architecture")
89
+ arch = arch_f.contents() if arch_f else None
90
+ if arch != SRC_ARCH:
91
+ logger.error("expected general.architecture=%s, found %r", SRC_ARCH, arch)
92
+ sys.exit(1)
93
+
94
+ bc = reader.get_field(f"{SRC_ARCH}.block_count")
95
+ nextn = reader.get_field(f"{SRC_ARCH}.nextn_predict_layers")
96
+ n_block = int(bc.contents())
97
+ n_nextn = int(nextn.contents()) if nextn else 0
98
+ if n_nextn != 1:
99
+ logger.error("this script handles exactly one MTP layer, file declares %d", n_nextn)
100
+ sys.exit(1)
101
+ mtp_il = args.mtp_layer if args.mtp_layer is not None else n_block - 1
102
+ src_prefix = f"blk.{mtp_il}."
103
+ logger.info("source block_count=%d, MTP module at blk.%d", n_block, mtp_il)
104
+
105
+ writer = gguf.GGUFWriter(path=None, arch=DST_ARCH, endianess=reader.endianess)
106
+
107
+ # ---- key/value metadata -------------------------------------------------------------
108
+ # Hyperparameters are re-prefixed rather than restated, so anything the parent knows about
109
+ # its own MLA, MoE and indexer geometry reaches the draft without being retyped here (and
110
+ # without silently drifting from the parent if the converter ever changes).
111
+ n_copied = 0
112
+ for field in reader.fields.values():
113
+ name = field.name
114
+ if name in ("GGUF.version", "GGUF.tensor_count", "GGUF.kv_count"):
115
+ continue
116
+ if name == "general.architecture":
117
+ continue
118
+ if any(name == SRC_ARCH + s for s in DROP_SUFFIXES):
119
+ logger.debug("dropping %s (not present in the MTP block)", name)
120
+ continue
121
+
122
+ val_type = field.types[0]
123
+ sub_type = field.types[-1] if val_type == gguf.GGUFValueType.ARRAY else None
124
+ value = field.contents()
125
+
126
+ if name.startswith(SRC_ARCH + "."):
127
+ suffix = name[len(SRC_ARCH):]
128
+ if suffix == ".block_count":
129
+ value = 1
130
+ elif suffix == ".leading_dense_block_count":
131
+ # The MTP block is a MoE block; there are no dense layers ahead of it here.
132
+ value = 0
133
+ elif suffix == ".attention.head_count_kv":
134
+ # Per-layer in the parent (0 on KDA layers, 1 on MLA). The draft has one MLA layer.
135
+ value = [1]
136
+ sub_type = gguf.GGUFValueType.INT32
137
+ name = DST_ARCH + suffix
138
+ elif name == "general.name":
139
+ value = str(value) + " MTP Draft"
140
+ elif name.startswith("quantize.imatrix."):
141
+ # The parent's imatrix provenance describes the parent, not this file.
142
+ continue
143
+
144
+ writer.add_key_value(name, value, val_type, sub_type=sub_type)
145
+ n_copied += 1
146
+
147
+ writer.add_key_value(f"{DST_ARCH}.mtp.parent_block", mtp_il, gguf.GGUFValueType.UINT32)
148
+ logger.info("copied %d kv pairs", n_copied)
149
+
150
+ # ---- tensors ------------------------------------------------------------------------
151
+ renames: dict[str, str] = {}
152
+ for t in reader.tensors:
153
+ if t.name in ("token_embd.weight", "output.weight"):
154
+ renames[t.name] = t.name
155
+ elif t.name.startswith(src_prefix):
156
+ tail = t.name[len(src_prefix):]
157
+ if tail == "nextn.shared_head_norm.weight":
158
+ renames[t.name] = "output_norm.weight"
159
+ else:
160
+ renames[t.name] = "blk.0." + tail
161
+
162
+ required = {
163
+ "token_embd.weight", "output.weight", "output_norm.weight",
164
+ "blk.0.nextn.eh_proj.weight", "blk.0.nextn.enorm.weight", "blk.0.nextn.hnorm.weight",
165
+ "blk.0.attn_norm.weight", "blk.0.attn_output.weight", "blk.0.ffn_norm.weight",
166
+ "blk.0.ffn_gate_inp.weight", "blk.0.ffn_down_exps.weight",
167
+ }
168
+ produced = set(renames.values())
169
+ missing = required - produced
170
+ if missing:
171
+ logger.error("source is missing required MTP tensors: %s", sorted(missing))
172
+ sys.exit(1)
173
+
174
+ keep = [t for t in reader.tensors if t.name in renames]
175
+ total = 0
176
+ for t in keep:
177
+ dst_name = renames[t.name]
178
+ writer.add_tensor_info(dst_name, t.data.shape, t.data.dtype, t.data.nbytes, t.tensor_type)
179
+ total += t.n_bytes
180
+ logger.debug("%-46s -> %s", t.name, dst_name)
181
+
182
+ logger.info("writing %d tensors, %.2f GiB to %s", len(keep), total / 2**30, args.dst)
183
+
184
+ tmp = args.dst.with_suffix(args.dst.suffix + ".part")
185
+ writer.open_output_file(tmp)
186
+ writer.write_header_to_file()
187
+ writer.write_kv_data_to_file()
188
+ writer.write_ti_data_to_file()
189
+ bar = tqdm(desc="writing", total=total, unit="B", unit_scale=True)
190
+ for t in keep:
191
+ writer.write_tensor_data(t.data, tensor_endianess=reader.endianess)
192
+ bar.update(t.n_bytes)
193
+ bar.close()
194
+ writer.close()
195
+
196
+ # Land the file only once it is complete on disk. A draft GGUF truncated by a power cut
197
+ # would otherwise sit there looking like a valid artifact.
198
+ os.replace(tmp, args.dst)
199
+ logger.info("done: %s (%.2f GiB)", args.dst, args.dst.stat().st_size / 2**30)
200
+
201
+
202
+ if __name__ == "__main__":
203
+ main()