File size: 12,962 Bytes
4606829
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Bounded CPU Coder390 BF16 -> MLX affine q4 conversion; never loads a model.

Sanitization is delegated to a SHA-pinned upstream mlx-vlm implementation.
Each source is fully hashed before use; source weights are never modified.
MTP remains in the source for a separate native sidecar extraction.
"""
from __future__ import annotations

import argparse
import gc
import hashlib
import importlib.util
import json
import math
from pathlib import Path
import shutil
import struct
import time
from types import SimpleNamespace

import mlx.core as mx
import numpy as np

ROOT = Path(__file__).resolve().parent
SANITIZER = ROOT / "raw/upstream/qwen3_5.py"
SANITIZER_SHA = "7c0e360a35e1f5d3819677cd6f7e4d7349f4f3dd2fad5fc8f1e374bd514e8f1b"
SANITIZER_REV = "952d4f6bc65bd5095e74abe71c78038764ee08aa"
DTYPES = {"BF16": (np.dtype("<u2"), mx.bfloat16),
          "F32": (np.dtype("<f4"), mx.float32),
          "F16": (np.dtype("<f2"), mx.float16)}
LINEAR_SUFFIXES = (".mlp.up_proj.weight", ".mlp.gate_proj.weight", ".mlp.down_proj.weight",
                   ".self_attn.q_proj.weight", ".self_attn.k_proj.weight", ".self_attn.v_proj.weight",
                   ".self_attn.o_proj.weight", ".linear_attn.in_proj_qkv.weight",
                   ".linear_attn.in_proj_z.weight", ".linear_attn.in_proj_a.weight",
                   ".linear_attn.in_proj_b.weight", ".linear_attn.out_proj.weight",
                   ".embed_tokens.weight", "lm_head.weight")


def sha256(path):
    digest = hashlib.sha256()
    with Path(path).open("rb") as handle:
        for block in iter(lambda: handle.read(8 * 1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def sanitizer():
    if sha256(SANITIZER) != SANITIZER_SHA:
        raise ValueError("Pinned sanitizer hash mismatch")
    spec = importlib.util.spec_from_file_location("mlx_vlm.models.qwen3_5._coder390_sanitize", SANITIZER)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module.Model.sanitize


def read_header(path):
    with path.open("rb") as handle:
        prefix = handle.read(8)
        if len(prefix) != 8:
            raise ValueError("Truncated safetensors header")
        length = struct.unpack("<Q", prefix)[0]
        if length > 16 * 1024 * 1024:
            raise ValueError("Safetensors header bound exceeded")
        raw = handle.read(length)
        if len(raw) != length:
            raise ValueError("Truncated safetensors header")
        header = json.loads(raw)
    entries = {key: value for key, value in header.items() if key != "__metadata__"}
    payload = path.stat().st_size - length - 8
    spans = []
    for key, meta in entries.items():
        if meta["dtype"] not in DTYPES:
            raise ValueError(f"Unsupported source dtype: {key}: {meta['dtype']}")
        start, end = meta["data_offsets"]
        shape = meta["shape"]
        if any(type(n) is not int or n < 0 for n in shape):
            raise ValueError(f"Invalid tensor shape: {key}")
        size = math.prod(shape) * DTYPES[meta["dtype"]][0].itemsize
        if start < 0 or end - start != size or end > payload:
            raise ValueError(f"Invalid source tensor offsets: {key}")
        spans.append((start, end))
    spans.sort()
    cursor = 0
    for start, end in spans:
        if start != cursor:
            raise ValueError("Safetensors payload gaps or overlaps")
        cursor = end
    if cursor != payload:
        raise ValueError("Safetensors payload size mismatch")
    return entries, 8 + length


def quantizable(name, shape):
    if name.startswith("model.visual."):
        return False
    if name.startswith("mtp."):
        return False
    if len(shape) == 2 and name.endswith(LINEAR_SUFFIXES):
        if shape[-1] % 64:
            raise ValueError(f"Unsupported group alignment: {name}")
        return True
    known = (".input_layernorm.weight", ".post_attention_layernorm.weight", ".norm.weight",
             ".q_norm.weight", ".k_norm.weight", ".conv1d.weight", ".A_log", ".dt_bias")
    if name.endswith(known):
        return False
    raise ValueError(f"Unsupported/unknown source tensor: {name}")


def tensor_bytes(array):
    mx.eval(array)
    dtype = array.dtype
    if dtype == mx.bfloat16:
        return np.asarray(array.view(mx.uint16), dtype="<u2").tobytes(), "BF16"
    if dtype == mx.float32:
        return np.asarray(array, dtype="<f4").tobytes(), "F32"
    if dtype == mx.float16:
        return np.asarray(array, dtype="<f2").tobytes(), "F16"
    if dtype == mx.uint32:
        return np.asarray(array, dtype="<u4").tobytes(), "U32"
    raise ValueError(f"Unsupported output dtype: {dtype}")


def pack_shard(output, pending, sequence):
    filename = f"model-{sequence:05d}.safetensors"
    header = {"__metadata__": {"format": "mlx"}}
    offset = 0
    for record in pending:
        end = offset + record["bytes"]
        header[record["name"]] = {"dtype": record["dtype"], "shape": record["shape"],
                                  "data_offsets": [offset, end]}
        offset = end
    raw = json.dumps(header, separators=(",", ":")).encode()
    raw += b" " * ((-len(raw)) % 8)
    path = output / filename
    with path.open("xb") as handle:
        handle.write(struct.pack("<Q", len(raw)))
        handle.write(raw)
        for record in pending:
            with record["path"].open("rb") as source:
                shutil.copyfileobj(source, handle, 8 * 1024 * 1024)
            record["path"].unlink()
    return filename


def convert(source, output, expected, *, row_chunk=128, shard_bytes=512 * 1024 * 1024):
    mx.set_default_device(mx.cpu)
    source, output = Path(source).resolve(), Path(output).resolve()
    if output.exists() or output == source or source in output.parents:
        raise ValueError("Destination exists or is inside source; refusing overwrite")
    if not 1 <= row_chunk <= 512:
        raise ValueError("row_chunk must be in 1..512")
    index = json.loads((source / "model.safetensors.index.json").read_text())["weight_map"]
    config = json.loads((source / "config.json").read_text())
    source_records = {}
    headers = {}
    for filename in sorted(set(index.values())):
        if Path(filename).name != filename:
            raise ValueError("Unsafe source shard path")
        path = source / filename
        want = expected.get(filename)
        if not want or path.stat().st_size != want["size"]:
            raise ValueError(f"Source size/manifest mismatch: {filename}")
        print(f"Verifying full SHA-256: {filename}", flush=True)
        digest = sha256(path)
        if digest != want["sha256"]:
            raise ValueError(f"Source SHA-256 mismatch: {filename}")
        source_records[filename] = {"size": path.stat().st_size, "sha256": digest}
        headers[filename] = read_header(path)
        if set(headers[filename][0]) != {key for key, value in index.items() if value == filename}:
            raise ValueError(f"Index/header mismatch: {filename}")
    output.mkdir(parents=True)
    spool = output / ".tensor-spool"
    spool.mkdir()
    sanitize = sanitizer()
    owner = SimpleNamespace(config=SimpleNamespace(
        text_config=SimpleNamespace(tie_word_embeddings=config["text_config"].get("tie_word_embeddings", False)),
        vision_config=SimpleNamespace(in_channels=config.get("vision_config", {}).get("in_channels", 3))))
    pending, weight_map, transforms = [], {}, []
    total_size, sequence, spool_id = 0, 1, 0
    started = time.monotonic()
    for number, (name, filename) in enumerate(index.items(), 1):
        if name.startswith("mtp."):
            continue
        meta, base = headers[filename]
        meta = meta[name]
        shape = meta["shape"]
        do_quant = quantizable(name, shape)
        dtype_np, dtype_mx = DTYPES[meta["dtype"]]
        mapped = np.memmap(source / filename, dtype=dtype_np, mode="r",
                           offset=base + meta["data_offsets"][0], shape=tuple(shape))
        rows = shape[0] if shape else 1
        records = {}
        for start in range(0, rows, row_chunk):
            part = np.array(mapped[start:start + row_chunk] if shape else mapped, copy=True)
            array = mx.array(part)
            if dtype_mx == mx.bfloat16:
                array = array.view(mx.bfloat16)
            if not bool(mx.all(mx.isfinite(array))):
                raise ValueError(f"Nonfinite source tensor: {name}")
            clean = sanitize(owner, {name: array})
            if len(clean) != 1:
                raise ValueError(f"Unexpected sanitizer output: {name}")
            new_name, array = next(iter(clean.items()))
            if do_quant:
                q, scale, bias = mx.quantize(array, group_size=64, bits=4, mode="affine")
                values = {new_name: q, new_name.removesuffix(".weight") + ".scales": scale,
                          new_name.removesuffix(".weight") + ".biases": bias}
            else:
                values = {new_name: array}
            for key, value in values.items():
                if not bool(mx.all(mx.isfinite(value))):
                    raise ValueError(f"Nonfinite converted tensor: {key}")
                data, kind = tensor_bytes(value)
                if key not in records:
                    spool_id += 1
                    path = spool / f"{spool_id:06d}.payload"
                    records[key] = {"name": key, "dtype": kind, "shape": list(value.shape), "bytes": 0, "path": path}
                    if shape:
                        records[key]["shape"][0] = 0
                record = records[key]
                if shape:
                    record["shape"][0] += value.shape[0]
                with record["path"].open("ab") as handle:
                    handle.write(data)
                record["bytes"] += len(data)
            del array, clean, values, part
            if do_quant:
                del q, scale, bias
            del value, data
        del mapped
        new_records = list(records.values())
        size = sum(record["bytes"] for record in new_records)
        if pending and sum(record["bytes"] for record in pending) + size > shard_bytes:
            shard = pack_shard(output, pending, sequence)
            for record in pending:
                weight_map[record["name"]] = shard
            pending = []
            sequence += 1
        pending.extend(new_records)
        total_size += size
        transforms.append({"source": name, "output": list(records), "quantized": do_quant})
        gc.collect()
        print(f"Converted {number}/{len(index)} {name} -> {size} bytes (CPU)", flush=True)
    if pending:
        shard = pack_shard(output, pending, sequence)
        for record in pending:
            if record["name"] in weight_map:
                raise ValueError("Duplicate converted tensor name")
            weight_map[record["name"]] = shard
    spool.rmdir()
    index_out = {"metadata": {"total_size": total_size}, "weight_map": dict(sorted(weight_map.items()))}
    (output / "model.safetensors.index.json").write_text(json.dumps(index_out, indent=2) + "\n")
    quantization = {"group_size": 64, "bits": 4, "mode": "affine"}
    config["quantization"] = quantization
    config["quantization_config"] = dict(quantization)
    (output / "config.json").write_text(json.dumps(config, indent=2) + "\n")
    for filename in ("tokenizer.json", "tokenizer_config.json", "chat_template.jinja", "generation_config.json",
                     "preprocessor_config.json", "video_preprocessor_config.json"):
        if (source / filename).is_file():
            shutil.copy2(source / filename, output / filename)
    files = {path.name: {"size": path.stat().st_size, "sha256": sha256(path)}
             for path in sorted(output.iterdir()) if path.is_file()}
    manifest = {"device": "cpu", "quantization": quantization, "vision": "source BF16, unquantized",
                "mtp": "excluded from target; original sidecar retained in source", "source_files": source_records,
                "sanitizer_revision": SANITIZER_REV, "sanitizer_sha256": SANITIZER_SHA,
                "row_chunk": row_chunk, "output_files": files, "transforms": transforms,
                "elapsed_s": time.monotonic() - started, "inference_qualified": False}
    (output / "conversion-manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
    return manifest


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--source", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--expected", type=Path, required=True)
    parser.add_argument("--row-chunk", type=int, default=128)
    args = parser.parse_args()
    result = convert(args.source, args.output, json.loads(args.expected.read_text()), row_chunk=args.row_chunk)
    print(json.dumps({key: result[key] for key in ["device", "elapsed_s", "inference_qualified"]}, indent=2))