Repository navigation
Expand file tree
/
Copy pathqwen4_pack.py
More file actions
3201 lines (2980 loc) · 123 KB
/
Copy pathqwen4_pack.py
File metadata and controls
3201 lines (2980 loc) · 123 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "huggingface-hub>=1.0",
# "numpy>=2.0",
# ]
# ///
"""Build the versioned DS4 Qwen3.8-Flash-Next fast pack.
The converter consumes the official BF16 safetensors checkpoint. It emits
one deterministic trunk GGUF, an SSD-backed Q4_1 PLE GGUF, and optional
vision/MTP GGUF sidecars. Unsloth/GGUF input is deliberately not a supported
source format: DS4 records and validates the official source revision and the
exact GGML block geometry used by its native kernels.
"""
from __future__ import annotations
import argparse
import concurrent.futures
import ctypes
import dataclasses
import hashlib
import json
import os
import shutil
import struct
import sys
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
from contextlib import contextmanager
from pathlib import Path
from typing import Iterable
import numpy as np
from huggingface_hub import get_token, hf_hub_download
from glm53_quantize import (
GGUF_ALIGNMENT,
GGUF_VERSION,
align,
kv_f32,
kv_string,
kv_u32,
kv_u64,
load_tokenizer_records,
pack_string,
)
ARCH = "qwen4-exp"
PACK_VERSION = 3
CONVERSION_STATE_VERSION = 4
MANIFEST_NAME = "qwen3.8-flash-next-q4.manifest.json"
STATE_NAME = "qwen3.8-flash-next-q4.conversion-state.json"
BASE_NAME = (
"Qwen3.8-Flash-Next-Q4KExperts-BF16Emb-BF16Control-"
"Q8GDN-Q8QSA-Q8Shared-Q8Out.gguf"
)
PLE_NAME = "Qwen3.8-Flash-Next-PLE-Q4_1.gguf"
VISION_NAME = "qwen3.8-flash-next-q4-vision.gguf"
MTP_NAME = "qwen3.8-flash-next-q4-mtp.gguf"
# Selected MTP routed-expert importance mode (None or "weight-energy").
MTP_IMATRIX_MODE: str | None = None
Q2_PACK_VERSION = 4
Q2_CONVERSION_STATE_VERSION = 1
Q2_MANIFEST_NAME = "qwen3.8-flash-next-q2.manifest.json"
Q2_STATE_NAME = "qwen3.8-flash-next-q2.conversion-state.json"
Q2_BASE_NAME = (
"Qwen3.8-Flash-Next-IQ2XXSGateUp-Q2KDown-BF16Emb-BF16Control-"
"Q8GDN-Q8QSA-Q8Shared-Q8Out.gguf"
)
Q2_PLE_NAME = "Qwen3.8-Flash-Next-Q2-PLE-Q4_1.gguf"
Q2_VISION_NAME = "qwen3.8-flash-next-q2-vision.gguf"
Q2_MTP_NAME = "qwen3.8-flash-next-q2-mtp.gguf"
Q2_IMATRIX_REPOSITORY = "unsloth/Qwen3.8-Flash-Next-GGUF"
Q2_IMATRIX_REVISION = "c8b5954a88c2775c546b92593eda40ea041d3176"
Q2_IMATRIX_SHA256 = (
"a5863123db1ca458727e738955bef7bfc199520aa2bee3a30142a1aff9254154"
)
LEGACY_ARTIFACT_NAMES = (
"qwen3.8-flash-next-q4.gguf",
"qwen3.8-flash-next-q4-ple.safetensors",
"qwen3.8-flash-next-q4-00001-of-00004.gguf",
"qwen3.8-flash-next-q4-00002-of-00004.gguf",
"qwen3.8-flash-next-q4-00003-of-00004.gguf",
"qwen3.8-flash-next-q4-00004-of-00004.gguf",
)
FREE_SPACE_RESERVE_BYTES = 32 * (1 << 30)
NGRAM_MARK = ".ple.ple_embedding.ngram_embedding.shard_"
PLE_AUX_SUFFIXES = (
".ple.ple_embedding.layer_multipliers",
".ple.ple_embedding.ngram_heads_offsets",
".ple.ple_embedding.ngram_heads_vocab_sizes",
)
PLE_WEIGHT_NAME = "ple.weight"
PLE_AUX_NAMES = (
"ple.layer_multipliers",
"ple.ngram_heads_offsets",
"ple.ngram_heads_vocab_sizes",
)
ARTIFACT_TENSOR_COUNTS = {
"base": 1211,
"vision": 333,
"mtp": 32,
"ple": 4,
}
QTYPE_F32 = 0
QTYPE_F16 = 1
QTYPE_Q4_1 = 3
QTYPE_Q8_0 = 8
QTYPE_Q2_K = 10
QTYPE_Q4_K = 12
QTYPE_IQ2_XXS = 16
QTYPE_I32 = 26
QTYPE_I64 = 27
QTYPE_BF16 = 30
DTYPE_TO_QTYPE = {
"F32": QTYPE_F32,
"F16": QTYPE_F16,
"Q4_1": QTYPE_Q4_1,
"Q8_0": QTYPE_Q8_0,
"Q2_K": QTYPE_Q2_K,
"Q4_K": QTYPE_Q4_K,
"IQ2_XXS": QTYPE_IQ2_XXS,
"I32": QTYPE_I32,
"U32": QTYPE_I32,
"I64": QTYPE_I64,
"BF16": QTYPE_BF16,
}
DTYPE_TO_NUMPY = {
"F32": np.dtype("<f4"),
"F16": np.dtype("<f2"),
"I32": np.dtype("<i4"),
"U32": np.dtype("<u4"),
"I64": np.dtype("<i8"),
"BF16": np.dtype("<u2"),
}
DTYPE_BYTES = {key: value.itemsize for key, value in DTYPE_TO_NUMPY.items()}
QTYPE_LAYOUT = {
"Q4_1": (32, 20),
"Q8_0": (32, 34),
"Q2_K": (256, 84),
"Q4_K": (256, 144),
"IQ2_XXS": (256, 66),
}
@dataclasses.dataclass(frozen=True)
class PackProfile:
name: str
pack_version: int
state_version: int
manifest_name: str
state_name: str
base_name: str
ple_name: str
vision_name: str
mtp_name: str
gate_up_qtype: str
down_qtype: str
required_ds4_version: str
pack_identity: str
Q4_PROFILE = PackProfile(
name="q4",
pack_version=PACK_VERSION,
state_version=CONVERSION_STATE_VERSION,
manifest_name=MANIFEST_NAME,
state_name=STATE_NAME,
base_name=BASE_NAME,
ple_name=PLE_NAME,
vision_name=VISION_NAME,
mtp_name=MTP_NAME,
gate_up_qtype="Q4_K",
down_qtype="Q4_K",
required_ds4_version="qwen3.8-flash-next-q4",
pack_identity="ds4-qwen3.8-flash-next-q4-v3",
)
Q2_PROFILE = PackProfile(
name="q2",
pack_version=Q2_PACK_VERSION,
state_version=Q2_CONVERSION_STATE_VERSION,
manifest_name=Q2_MANIFEST_NAME,
state_name=Q2_STATE_NAME,
base_name=Q2_BASE_NAME,
ple_name=Q2_PLE_NAME,
vision_name=Q2_VISION_NAME,
mtp_name=Q2_MTP_NAME,
gate_up_qtype="IQ2_XXS",
down_qtype="Q2_K",
required_ds4_version="qwen3.8-flash-next-q2",
pack_identity="ds4-qwen3.8-flash-next-q2-v4",
)
PACK_PROFILES = {profile.name: profile for profile in (Q4_PROFILE, Q2_PROFILE)}
CONFIG = {
"layers": 48,
"hidden": 2560,
"vocab": 248320,
"context": 262144,
"attn_heads": 24,
"kv_heads": 2,
"head_dim": 256,
"rope_dim": 64,
"rope_theta": 10_000_000.0,
"full_attention_interval": 4,
"linear_key_heads": 16,
"linear_value_heads": 48,
"linear_head_dim": 128,
"linear_conv": 4,
"experts": 512,
"experts_used": 10,
"expert_ff": 640,
"shared_ff": 640,
"hc_count": 4,
"hc_lowrank": 320,
"qsa_heads": 4,
"qsa_kv_heads": 1,
"qsa_dim": 128,
"qsa_topk": 2048,
"qsa_ratio": 4,
# Checkpoint config uses one-indexed layer ids; the runtime stores index 1.
"ple_layer_ids": (2,),
"ple_layer": 1,
"ple_dim": 2560,
"ple_row_dim": 160,
"ple_rows": 320_001_536,
"ple_conv": 4,
"ngram_size": 3,
"heads_per_ngram": 8,
"ngram_vocab_base": 20_000_000,
"ngram_vocab_divisor": 128,
"ngram_seed": 1234,
"split_ngram_parts": 128,
"output_gate_type": "sigmoid",
# The model-config EOS is the PLE history-reset token. Generation uses
# the tokenizer's <|im_end|> token instead.
"ngram_eos": 248044,
"generation_eos": 248046,
"image_token": 248056,
"vision_start_token": 248053,
"vision_end_token": 248054,
"rms_eps": 1.0e-6,
"routed_down_physical_input": 768,
"vision_fc2_physical_input": 4320,
}
NORM_FOLD_SUFFIXES = (
"hc_norm.weight",
"q_norm.weight",
"k_norm.weight",
"q_layernorm.weight",
"k_layernorm.weight",
"ple.norm_key.weight",
"ple.norm_query.weight",
"ple.norm_conv.weight",
"pre_fc_norm_embedding.weight",
"pre_fc_norm_hidden.weight",
)
def fail(message: str):
raise ValueError(message)
def pack_profile(value: str | PackProfile | None = None) -> PackProfile:
if isinstance(value, PackProfile):
return value
try:
return PACK_PROFILES[value or "q4"]
except KeyError:
fail(f"unknown Qwen pack profile {value!r}")
def profile_from_args(args) -> PackProfile:
return pack_profile(getattr(args, "profile", "q4"))
def product(values: Iterable[int]) -> int:
result = 1
for value in values:
result *= value
return result
def sha256_file(path: Path, offset: int = 0, length: int | None = None) -> str:
digest = hashlib.sha256()
with path.open("rb") as fp:
fp.seek(offset)
remaining = length
while remaining is None or remaining:
amount = 16 << 20 if remaining is None else min(16 << 20, remaining)
data = fp.read(amount)
if not data:
if remaining not in (None, 0):
fail(f"short read while hashing {path}")
break
digest.update(data)
if remaining is not None:
remaining -= len(data)
return digest.hexdigest()
def decode_safetensors_header(raw_length: bytes, raw_header: bytes,
source: str) -> tuple[dict, int]:
if len(raw_length) != 8:
fail(f"{source}: truncated safetensors header")
length = struct.unpack("<Q", raw_length)[0]
if length == 0 or length > 1 << 30:
fail(f"{source}: invalid safetensors header size {length}")
if len(raw_header) != length:
fail(f"{source}: truncated safetensors JSON header")
header = json.loads(raw_header)
header.pop("__metadata__", None)
return header, 8 + length
def read_safetensors_header(path: Path) -> tuple[dict, int]:
with path.open("rb") as fp:
raw_length = fp.read(8)
if len(raw_length) != 8:
fail(f"{path}: truncated safetensors header")
length = struct.unpack("<Q", raw_length)[0]
if length == 0 or length > 1 << 30:
fail(f"{path}: invalid safetensors header size {length}")
raw_header = fp.read(length)
return decode_safetensors_header(raw_length, raw_header, os.fspath(path))
def validate_hub_filename(filename: str) -> str:
path = Path(filename)
if not filename or path.is_absolute() or ".." in path.parts:
fail(f"unsafe Hub checkpoint filename: {filename!r}")
return filename
def hub_file_url(repo_id: str, revision: str, filename: str) -> str:
if not repo_id or not revision:
fail("remote source requires a repository and immutable revision")
filename = validate_hub_filename(filename)
return (
"https://huggingface.co/"
+ urllib.parse.quote(repo_id, safe="/")
+ "/resolve/"
+ urllib.parse.quote(revision, safe="")
+ "/"
+ urllib.parse.quote(filename, safe="/")
)
def read_hub_range(repo_id: str, revision: str, filename: str,
begin: int, end: int, token: str | None) -> tuple[bytes, int]:
headers = {"Range": f"bytes={begin}-{end}"}
if token:
headers["Authorization"] = f"Bearer {token}"
url = hub_file_url(repo_id, revision, filename)
last_error = None
for attempt in range(6):
request = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(request, timeout=120) as response:
if response.status != 206:
fail(
f"Hub range request for {filename} returned HTTP "
f"{response.status}, expected 206"
)
content_range = response.headers.get("Content-Range", "")
try:
total = int(content_range.rsplit("/", 1)[1])
except (IndexError, ValueError):
fail(
f"Hub range response for {filename} has no total size"
)
expected = end - begin + 1
data = response.read(expected + 1)
if len(data) != expected:
raise OSError(
f"short Hub range read: got {len(data)}, expected {expected}"
)
return data, total
except urllib.error.HTTPError as error:
if error.code not in (408, 429, 500, 502, 503, 504):
raise
last_error = error
except (urllib.error.URLError, TimeoutError, ConnectionError,
OSError) as error:
last_error = error
if attempt + 1 < 6:
time.sleep(min(2 ** attempt, 16))
fail(f"Hub range request for {filename} failed after retries: {last_error}")
def read_hub_safetensors_header(repo_id: str, revision: str, filename: str,
token: str | None) -> tuple[dict, int, int]:
probe_size = 1 << 20
probe, total = read_hub_range(
repo_id, revision, filename, 0, probe_size - 1, token
)
raw_length = probe[:8]
length = struct.unpack("<Q", raw_length)[0]
if length == 0 or length > 1 << 30:
fail(f"{filename}: invalid remote safetensors header size {length}")
if 8 + length <= len(probe):
raw_header = probe[8:8 + length]
else:
raw_header, confirmed_total = read_hub_range(
repo_id, revision, filename, 8, 7 + length, token
)
if confirmed_total != total:
fail(f"Hub object size changed while reading {filename}")
header, data_offset = decode_safetensors_header(
raw_length, raw_header, f"{repo_id}@{revision}/{filename}"
)
return header, data_offset, total
class SourceDB:
def __init__(self, root: Path, remote_repo: str | None = None,
revision: str | None = None, token: str | None = None):
self.root = root
self.remote_repo = remote_repo
self.revision = revision
self.token = token
self.active_paths: dict[str, Path] = {}
config_path = root / "config.json"
if not config_path.is_file():
fail(f"missing {config_path}")
self.config = json.loads(config_path.read_text())
if self.config.get("quantization_config") or self.config.get("quantization"):
fail("the DS4 pack requires the official dense checkpoint; direct quantized/Unsloth input is unsupported")
index_path = root / "model.safetensors.index.json"
if index_path.is_file():
document = json.loads(index_path.read_text())
self.weight_map = document.get("weight_map")
if not isinstance(self.weight_map, dict) or not self.weight_map:
fail(f"{index_path}: missing weight_map")
elif (root / "model.safetensors").is_file():
header, _ = read_safetensors_header(root / "model.safetensors")
self.weight_map = {name: "model.safetensors" for name in header}
else:
fail(f"{root}: no safetensors checkpoint found")
self.tensors: dict[str, dict] = {}
self.shards: dict[str, dict] = {}
source_filenames = sorted(set(self.weight_map.values()))
for ordinal, filename in enumerate(source_filenames, 1):
validate_hub_filename(filename)
path = root / filename
if path.is_file():
header, data_offset = read_safetensors_header(path)
file_size = path.stat().st_size
elif remote_repo:
if not revision:
fail("--remote-repo requires --source-revision")
if ordinal == 1 or ordinal % 10 == 0 or ordinal == len(source_filenames):
print(
f"discovering remote source headers "
f"{ordinal}/{len(source_filenames)}",
flush=True,
)
header, data_offset, file_size = read_hub_safetensors_header(
remote_repo, revision, filename, token
)
else:
fail(
f"missing source shard {path}; use --remote-repo to "
"stream official shards through bounded staging"
)
self.shards[filename] = {
"path": path if path.is_file() else None,
"size": file_size,
"data_offset": data_offset,
}
for name, info in header.items():
if self.weight_map.get(name) != filename:
fail(f"source index assigns {name} to the wrong shard")
if name in self.tensors:
fail(f"duplicate source tensor {name}")
begin, end = info["data_offsets"]
dtype = info["dtype"]
shape = tuple(int(value) for value in info["shape"])
if dtype not in DTYPE_TO_NUMPY:
fail(f"{name}: unsupported source dtype {dtype}")
if end - begin != product(shape) * DTYPE_BYTES[dtype]:
fail(f"{name}: source payload size does not match dtype/shape")
self.tensors[name] = {
"filename": filename,
"path": path if path.is_file() else None,
"offset": data_offset + begin,
"nbytes": end - begin,
"dtype": dtype,
"shape": shape,
}
if set(self.tensors) != set(self.weight_map):
missing = sorted(set(self.weight_map) - set(self.tensors))
fail(f"source checkpoint is incomplete; first missing tensor: {missing[0]}")
def activate_shard(self, filename: str, path: Path):
if filename not in self.shards or not path.is_file():
fail(f"cannot activate unavailable source shard {filename}")
self.active_paths[filename] = path
def deactivate_shard(self, filename: str):
self.active_paths.pop(filename, None)
def read_metadata_file(self, filename: str,
max_bytes: int = 16 << 20) -> bytes:
validate_hub_filename(filename)
path = self.root / filename
if path.is_file():
data = path.read_bytes()
elif self.remote_repo and self.revision:
_, total = read_hub_range(
self.remote_repo, self.revision, filename, 0, 0, self.token
)
if total <= 0 or total > max_bytes:
fail(
f"remote metadata {filename} is {total} bytes, outside "
f"the allowed range"
)
data, confirmed = read_hub_range(
self.remote_repo, self.revision, filename,
0, total - 1, self.token
)
if confirmed != total:
fail(f"Hub object size changed while reading {filename}")
else:
fail(f"missing source metadata {path}")
if not data or len(data) > max_bytes:
fail(f"source metadata {filename} is empty or too large")
return data
def read(self, name: str) -> np.ndarray:
try:
info = self.tensors[name]
except KeyError:
fail(f"source tensor not found: {name}")
path = info["path"] or self.active_paths.get(info["filename"])
if not path:
fail(
f"source shard {info['filename']} is not materialized for "
f"tensor {name}"
)
with path.open("rb") as fp:
fp.seek(info["offset"])
raw = fp.read(info["nbytes"])
if len(raw) != info["nbytes"]:
fail(f"short payload read for {name}")
return np.frombuffer(raw, dtype=DTYPE_TO_NUMPY[info["dtype"]]).reshape(info["shape"])
@contextmanager
def materialize(self, filename: str, staging_root: Path):
shard = self.shards.get(filename)
if shard is None:
fail(f"unknown source shard {filename}")
if shard["path"]:
self.activate_shard(filename, shard["path"])
try:
yield shard["path"]
finally:
self.deactivate_shard(filename)
return
if not self.remote_repo or not self.revision:
fail(f"source shard {filename} is unavailable")
staging_root.mkdir(parents=True, exist_ok=True)
temporary = Path(tempfile.mkdtemp(prefix="shard-", dir=staging_root))
try:
downloaded = Path(hf_hub_download(
repo_id=self.remote_repo,
filename=filename,
revision=self.revision,
token=self.token,
cache_dir=temporary / "cache",
))
if downloaded.stat().st_size != shard["size"]:
fail(
f"downloaded {filename} has {downloaded.stat().st_size} "
f"bytes, expected {shard['size']}"
)
self.activate_shard(filename, downloaded)
try:
yield downloaded
finally:
self.deactivate_shard(filename)
finally:
shutil.rmtree(temporary, ignore_errors=True)
def text_config(document: dict) -> dict:
candidate = document.get("text_config")
return candidate if isinstance(candidate, dict) else document
def config_value(config: dict, *names, default=None):
for name in names:
if name in config:
return config[name]
return default
def validate_source_config(document: dict):
config = text_config(document)
root_type = document.get("model_type")
model_type = config.get("model_type", root_type)
if model_type not in ("qwen4_exp", "qwen4_exp_text"):
fail(f"source model_type is {model_type!r}, expected qwen4_exp")
checks = {
"num_hidden_layers": CONFIG["layers"],
"hidden_size": CONFIG["hidden"],
"vocab_size": CONFIG["vocab"],
"max_position_embeddings": CONFIG["context"],
"num_attention_heads": CONFIG["attn_heads"],
"num_key_value_heads": CONFIG["kv_heads"],
"head_dim": CONFIG["head_dim"],
"full_attention_interval": CONFIG["full_attention_interval"],
"hc_count": CONFIG["hc_count"],
"hc_lowrank": CONFIG["hc_lowrank"],
"linear_num_key_heads": CONFIG["linear_key_heads"],
"linear_num_value_heads": CONFIG["linear_value_heads"],
"linear_key_head_dim": CONFIG["linear_head_dim"],
"linear_value_head_dim": CONFIG["linear_head_dim"],
"linear_conv_kernel_dim": CONFIG["linear_conv"],
"indexer_n_heads": CONFIG["qsa_heads"],
"indexer_kv_heads": CONFIG["qsa_kv_heads"],
"indexer_head_dim": CONFIG["qsa_dim"],
"indexer_budget": CONFIG["qsa_topk"],
"indexer_compress_ratio": CONFIG["qsa_ratio"],
"num_experts": CONFIG["experts"],
"num_experts_per_tok": CONFIG["experts_used"],
"moe_intermediate_size": CONFIG["expert_ff"],
"shared_expert_intermediate_size": CONFIG["shared_ff"],
"ple_embed_dim": CONFIG["ple_dim"],
"ple_conv_kernel_size": CONFIG["ple_conv"],
"ngram_size": CONFIG["ngram_size"],
"heads_per_ngram": CONFIG["heads_per_ngram"],
"ngram_vocab_size_base": CONFIG["ngram_vocab_base"],
"make_ngram_vocab_size_divisible_by": CONFIG["ngram_vocab_divisor"],
"split_ngram_parts": CONFIG["split_ngram_parts"],
"output_gate_type": CONFIG["output_gate_type"],
"eos_token_id": CONFIG["ngram_eos"],
}
aliases = {
"num_experts": ("num_experts", "num_local_experts"),
"num_experts_per_tok": ("num_experts_per_tok", "num_experts_per_token"),
}
for name, expected in checks.items():
actual = config_value(config, *aliases.get(name, (name,)))
if actual != expected:
fail(f"source config {name}={actual!r}, expected {expected}")
if tuple(config.get("ple_layer_ids", ())) != CONFIG["ple_layer_ids"]:
fail(
f"source config ple_layer_ids={config.get('ple_layer_ids')!r}, "
f"expected {list(CONFIG['ple_layer_ids'])}"
)
if config.get("seed", CONFIG["ngram_seed"]) != CONFIG["ngram_seed"]:
fail(
f"source config seed={config.get('seed')!r}, "
f"expected {CONFIG['ngram_seed']}"
)
layer_types = config.get("layer_types")
if not isinstance(layer_types, list) or len(layer_types) != CONFIG["layers"]:
fail("source config has missing or invalid layer_types")
for layer, layer_type in enumerate(layer_types):
expected = "full_attention" if (layer + 1) % CONFIG["full_attention_interval"] == 0 else "linear_attention"
if layer_type not in (expected, "qwen_sparse_attention" if expected == "full_attention" else expected):
fail(
f"source layer {layer} type is {layer_type!r}, expected {expected!r}"
)
rope = config.get("rope_parameters", config)
rope_dim = config_value(config, "partial_rotary_factor")
if rope_dim is not None:
rope_dim = round(float(rope_dim) * CONFIG["head_dim"])
else:
rope_dim = config_value(config, "rotary_dim", "rope_dim", default=CONFIG["rope_dim"])
if rope_dim != CONFIG["rope_dim"]:
fail(f"source partial RoPE dimension is {rope_dim}, expected {CONFIG['rope_dim']}")
theta = config_value(rope, "rope_theta", default=config.get("rope_theta"))
if theta is not None and float(theta) != CONFIG["rope_theta"]:
fail(f"source RoPE theta is {theta}, expected {CONFIG['rope_theta']}")
def renamed(name: str) -> str:
if name.startswith("model.language_model."):
return "language_model.model." + name[len("model.language_model."):]
if name.startswith("mtp."):
return "language_model.mtp." + name[len("mtp."):]
if name == "lm_head.weight":
return "language_model.lm_head.weight"
return name
def needs_norm_fold(name: str) -> bool:
return name.endswith(NORM_FOLD_SUFFIXES)
def needs_hc_divisor_fold(name: str) -> bool:
return name.endswith((
".input_mix_weight_down.weight",
".block_inject_weight.weight",
))
def f32_to_bf16(values: np.ndarray) -> np.ndarray:
bits = np.asarray(values, dtype="<f4").view("<u4")
rounded = bits + np.uint32(0x7FFF) + ((bits >> 16) & 1)
return (rounded >> 16).astype("<u2")
def bf16_to_f32(values: np.ndarray) -> np.ndarray:
return (np.asarray(values, dtype="<u2").astype("<u4") << 16).view("<f4")
GGUF_VALUE_UINT8 = 0
GGUF_VALUE_INT8 = 1
GGUF_VALUE_UINT16 = 2
GGUF_VALUE_INT16 = 3
GGUF_VALUE_UINT32 = 4
GGUF_VALUE_INT32 = 5
GGUF_VALUE_FLOAT32 = 6
GGUF_VALUE_BOOL = 7
GGUF_VALUE_STRING = 8
GGUF_VALUE_ARRAY = 9
GGUF_VALUE_UINT64 = 10
GGUF_VALUE_INT64 = 11
GGUF_VALUE_FLOAT64 = 12
GGUF_SCALAR_FORMATS = {
GGUF_VALUE_UINT8: "<B",
GGUF_VALUE_INT8: "<b",
GGUF_VALUE_UINT16: "<H",
GGUF_VALUE_INT16: "<h",
GGUF_VALUE_UINT32: "<I",
GGUF_VALUE_INT32: "<i",
GGUF_VALUE_FLOAT32: "<f",
GGUF_VALUE_BOOL: "<?",
GGUF_VALUE_UINT64: "<Q",
GGUF_VALUE_INT64: "<q",
GGUF_VALUE_FLOAT64: "<d",
}
def read_exact(fp, length: int, label: str) -> bytes:
data = fp.read(length)
if len(data) != length:
fail(f"short read for {label}")
return data
def read_u32(fp, label: str) -> int:
return struct.unpack("<I", read_exact(fp, 4, label))[0]
def read_u64(fp, label: str) -> int:
return struct.unpack("<Q", read_exact(fp, 8, label))[0]
def read_gguf_string(fp, label: str) -> str:
length = read_u64(fp, f"{label} length")
if length > 1 << 30:
fail(f"unreasonable {label} length {length}")
try:
return read_exact(fp, length, label).decode("utf-8")
except UnicodeDecodeError as error:
fail(f"{label} is not valid UTF-8: {error}")
def read_gguf_value(fp, value_type: int, label: str):
if value_type == GGUF_VALUE_STRING:
return read_gguf_string(fp, label)
if value_type == GGUF_VALUE_ARRAY:
element_type = read_u32(fp, f"{label} array type")
count = read_u64(fp, f"{label} array count")
if count > 1 << 32:
fail(f"unreasonable {label} array count {count}")
if element_type == GGUF_VALUE_STRING:
return [
read_gguf_string(fp, f"{label} array item")
for _ in range(count)
]
fmt = GGUF_SCALAR_FORMATS.get(element_type)
if fmt is None:
fail(f"unsupported {label} GGUF array type {element_type}")
size = struct.calcsize(fmt)
raw = read_exact(fp, count * size, label)
return list(struct.unpack(f"<{count}{fmt[-1]}", raw))
fmt = GGUF_SCALAR_FORMATS.get(value_type)
if fmt is None:
fail(f"unsupported {label} GGUF value type {value_type}")
return struct.unpack(fmt, read_exact(fp, struct.calcsize(fmt), label))[0]
@dataclasses.dataclass(frozen=True)
class ImatrixTensor:
shape: tuple[int, ...]
qtype: int
offset: int
nbytes: int
class QwenGGUFImatrix:
"""Validated, mmap-backed Qwen expert importance statistics.
llama.cpp's GGUF imatrix stores raw input-square sums and a separate
count for every routed expert. Keeping the 553 MB file mapped avoids a
second resident copy while source shards are being quantized.
"""
def __init__(self, path: Path, expected_sha256: str | None = None,
repository: str = Q2_IMATRIX_REPOSITORY,
revision: str = Q2_IMATRIX_REVISION):
self.path = Path(path)
if not self.path.is_file():
fail(f"Q2 imatrix not found: {self.path}")
self.sha256 = sha256_file(self.path)
if expected_sha256 is not None and self.sha256 != expected_sha256:
fail(
f"Q2 imatrix checksum mismatch: expected {expected_sha256}, "
f"got {self.sha256}"
)
self.repository = repository
self.revision = revision
self.metadata: dict[str, object] = {}
self.tensors: dict[str, ImatrixTensor] = {}
self.entries: dict[str, tuple[np.ndarray, np.ndarray]] = {}
self.fallback_entries: list[dict[str, int | str]] = []
self._mapping = np.memmap(self.path, dtype=np.uint8, mode="r")
self._parse()
self._validate_qwen_entries()
def _parse(self):
file_size = self.path.stat().st_size
with self.path.open("rb") as fp:
if read_exact(fp, 4, "imatrix GGUF magic") != b"GGUF":
fail(f"{self.path}: Q2 imatrix is not a GGUF file")
version = read_u32(fp, "imatrix GGUF version")
if version != GGUF_VERSION:
fail(
f"{self.path}: Q2 imatrix uses GGUF v{version}, "
f"expected v{GGUF_VERSION}"
)
tensor_count = read_u64(fp, "imatrix tensor count")
metadata_count = read_u64(fp, "imatrix metadata count")
if tensor_count == 0 or tensor_count > 1 << 20:
fail(f"{self.path}: invalid imatrix tensor count {tensor_count}")
if metadata_count == 0 or metadata_count > 1 << 20:
fail(
f"{self.path}: invalid imatrix metadata count "
f"{metadata_count}"
)
for _ in range(metadata_count):
key = read_gguf_string(fp, "imatrix metadata key")
if key in self.metadata:
fail(f"{self.path}: duplicate imatrix metadata key {key}")
value_type = read_u32(fp, f"imatrix metadata type for {key}")
self.metadata[key] = read_gguf_value(
fp, value_type, f"imatrix metadata {key}"
)
directories = []
for _ in range(tensor_count):
name = read_gguf_string(fp, "imatrix tensor name")
if name in self.tensors or any(row[0] == name for row in directories):
fail(f"{self.path}: duplicate imatrix tensor {name}")
dimensions = read_u32(fp, f"imatrix dimensions for {name}")
if dimensions == 0 or dimensions > 4:
fail(
f"{self.path}: invalid imatrix rank {dimensions} "
f"for {name}"
)
shape = tuple(
read_u64(fp, f"imatrix shape for {name}")
for _ in range(dimensions)
)
if any(value == 0 or value > 1 << 32 for value in shape):
fail(f"{self.path}: invalid imatrix shape {shape} for {name}")
qtype = read_u32(fp, f"imatrix qtype for {name}")
offset = read_u64(fp, f"imatrix offset for {name}")
directories.append((name, shape, qtype, offset))
data_offset = align(fp.tell())
for name, shape, qtype, offset in directories:
if qtype != QTYPE_F32:
fail(f"{self.path}: imatrix tensor {name} is not F32")
nbytes = product(shape) * 4
absolute = data_offset + offset
if absolute < data_offset or absolute + nbytes > file_size:
fail(f"{self.path}: imatrix tensor {name} is out of bounds")
self.tensors[name] = ImatrixTensor(
shape=shape, qtype=qtype, offset=absolute, nbytes=nbytes
)
if self.metadata.get("general.type") != "imatrix":
fail(f"{self.path}: GGUF general.type is not imatrix")
datasets = self.metadata.get("imatrix.datasets")
if (not isinstance(datasets, list) or not datasets or
any(not isinstance(item, str) or not item for item in datasets)):
fail(f"{self.path}: missing or invalid imatrix.datasets metadata")
for key in ("imatrix.chunk_count", "imatrix.chunk_size"):
value = self.metadata.get(key)
if not isinstance(value, int) or value <= 0:
fail(f"{self.path}: missing or invalid {key} metadata")
def _array(self, tensor: ImatrixTensor) -> np.ndarray:
return np.frombuffer(
self._mapping, dtype="<f4", count=product(tensor.shape),
offset=tensor.offset,
)
def _validate_qwen_entries(self):
for layer in range(CONFIG["layers"]):
for part, width in (
("gate", CONFIG["hidden"]),
("up", CONFIG["hidden"]),
("down", CONFIG["expert_ff"])):
base = f"blk.{layer}.ffn_{part}_exps.weight"
sums_name = base + ".in_sum2"
counts_name = base + ".counts"
sums_tensor = self.tensors.get(sums_name)
counts_tensor = self.tensors.get(counts_name)
if sums_tensor is None or counts_tensor is None:
missing = sums_name if sums_tensor is None else counts_name
fail(f"{self.path}: required Q2 imatrix tensor is missing: {missing}")
expected_sums = (width, CONFIG["experts"])
expected_counts = (1, CONFIG["experts"])
if sums_tensor.shape != expected_sums:
fail(
f"{self.path}: {sums_name} has shape "
f"{sums_tensor.shape}, expected {expected_sums}"
)
if counts_tensor.shape != expected_counts:
fail(
f"{self.path}: {counts_name} has shape "
f"{counts_tensor.shape}, expected {expected_counts}"
)
sums = self._array(sums_tensor).reshape(CONFIG["experts"], width)
counts = self._array(counts_tensor)
if not np.all(np.isfinite(sums)) or np.any(sums < 0.0):
fail(f"{self.path}: {sums_name} has nonfinite/negative statistics")
if (not np.all(np.isfinite(counts)) or
np.any(counts < 0.0) or
not np.all(counts == np.rint(counts))):
fail(f"{self.path}: {counts_name} has invalid counts")
self.entries[base] = (sums, counts)
self.fallback_entries.extend(
{
"tensor": base,
"expert": int(expert),
"part": part,
}
for expert in np.flatnonzero(counts == 0.0)
)
if self.fallback_entries:
gate_up = sum(
entry["part"] in ("gate", "up")
for entry in self.fallback_entries
)
down = self.fallback_count - gate_up
print(
"qwen4-pack: Q2 imatrix has "
f"{self.fallback_count} zero-count expert entries "
f"(gate/up={gate_up}, down={down}); using per-expert "
"weight-energy fallback",
file=sys.stderr,
flush=True,
)
@property
def fallback_count(self) -> int:
return len(self.fallback_entries)
def expert_weights(self, name: str, expert: int,
values: np.ndarray) -> np.ndarray:
try:
sums, counts = self.entries[name]
except KeyError:
fail(f"required Q2 imatrix entry is missing: {name}")
if expert < 0 or expert >= CONFIG["experts"]:
fail(f"invalid Q2 routed expert index {expert}")
count = counts[expert]
if count > 0.0:
return np.ascontiguousarray(sums[expert] / count, dtype="<f4")
source = bf16_to_f32(values)
weights = np.square(source, dtype=np.float32).sum(
axis=0, dtype=np.float32
)
if not np.all(np.isfinite(weights)):
fail(f"{name} expert {expert}: nonfinite weight-energy fallback")
return np.ascontiguousarray(weights, dtype="<f4")
def provenance(self) -> dict:
return {
"format": "gguf-imatrix-v3",
"repository": self.repository,
"revision": self.revision,
"sha256": self.sha256,