Download mlx_agent_tools/stream_convert.py from ChengyiX/mlx-agent-tools: direct link, hf CLI and curl.
- Browser
- Download file 13 kB
-
https://huggingface.co/datasets/ChengyiX/mlx-agent-tools/resolve/main/mlx_agent_tools/stream_convert.py
- Command line
-
hf download hf://datasets/ChengyiX/mlx-agent-tools/mlx_agent_tools/stream_convert.py
-
curl -L -o stream_convert.py https://huggingface.co/datasets/ChengyiX/mlx-agent-tools/resolve/main/mlx_agent_tools/stream_convert.py
13 kB
| """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)) | |