File size: 3,811 Bytes
e9a2b5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Quantize a converted MLX checkpoint.

    python -m ming_mlx.quantize --src weights_mlx --dst weights_mlx_q8 \
        --llm-bits 8 --dit-bits 8 [--group-size 64]

Quantized (affine, mx.quantize):
  llm: attention qkv/dense, dense MLP, shared experts, routed experts (SwitchGLU)
  dit: attention to_q/k/v/out and feed_forward w1/w2/w3 in every block
Kept in bf16: VAE, all norms, embeddings (word_embeddings,
x/cap embedders, pad tokens), routers, timestep embedder, adaLN modulation,
final layer, and the connector/projections.
"""
from __future__ import annotations

import argparse
import json
import os
import re
import shutil
from pathlib import Path

import mlx.core as mx
import mlx.nn as nn

LLM_PATTERNS = [r"\.attention\.(query_key_value|dense)$", r"\.mlp\.(gate_proj|up_proj|down_proj)$",
                r"\.shared_experts\.(gate_proj|up_proj|down_proj)$", r"\.switch_mlp\.(gate_proj|up_proj|down_proj)$"]
DIT_PATTERNS = [r"\.attention\.(to_q|to_k|to_v)$", r"\.attention\.to_out\.0$", r"\.feed_forward\.(w1|w2|w3)$"]


def _predicate(name):
    pats = LLM_PATTERNS if name == "llm" else DIT_PATTERNS

    def pred(path, module):
        return hasattr(module, "to_quantized") and any(re.search(p, path) for p in pats)

    return pred


def quantize_module(module: nn.Module, name: str, bits: int, group_size: int = 64):
    nn.quantize(module, group_size=group_size, bits=bits, class_predicate=_predicate(name))
    return module


def main(argv=None):
    ap = argparse.ArgumentParser()
    ap.add_argument("--src", type=Path, required=True)
    ap.add_argument("--dst", type=Path, required=True)
    ap.add_argument("--llm-bits", type=int, default=0, help="0 = keep bf16")
    ap.add_argument("--dit-bits", type=int, default=0, help="0 = keep bf16")
    ap.add_argument("--group-size", type=int, default=64)
    args = ap.parse_args(argv)
    from .pipeline import MingPipeline

    src, dst = args.src, args.dst
    dst.mkdir(parents=True, exist_ok=True)
    cfg = json.loads((src / "config.json").read_text())
    index = json.loads((src / "index.json").read_text())
    qcfg, new_index = {}, {}
    pipe = MingPipeline.load(src)

    def link(prefix):
        for f in sorted({f for f in index.values() if f.startswith(prefix)}):
            if not (dst / f).exists():
                shutil.copy2((src / f).resolve(), dst / f)
        new_index.update({k: f for k, f in index.items() if f.startswith(prefix)})

    for name, bits, loader in (("dit", args.dit_bits, "load_dit"), ("llm", args.llm_bits, "load_encoder")):
        if not bits:
            link(name)
            continue
        getattr(pipe, loader)()
        module = pipe.dit if name == "dit" else pipe.llm
        quantize_module(module, name, bits, args.group_size)
        from mlx.utils import tree_flatten
        w = dict(tree_flatten(module.parameters()))
        fname = f"{name}-q{bits}.safetensors"
        mx.save_safetensors(str(dst / fname), w)
        new_index.update({k: fname for k in w})
        qcfg[name] = {"bits": bits, "group_size": args.group_size}
        if name == "dit":
            pipe.dit = None
        else:
            pipe.release_encoder()
        mx.clear_cache()
    for f in ("cond.safetensors", "vae.safetensors"):
        if not (dst / f).exists():
            shutil.copy2((src / f).resolve(), dst / f)
    new_index.update({k: f for k, f in index.items() if f in ("cond.safetensors", "vae.safetensors")})
    if not (dst / "tokenizer").exists():
        shutil.copytree(src / "tokenizer", dst / "tokenizer")
    (dst / "config.json").write_text(json.dumps(cfg, indent=2))
    (dst / "index.json").write_text(json.dumps(new_index, indent=1))
    (dst / "quantization.json").write_text(json.dumps(qcfg, indent=2))
    print(json.dumps(qcfg))


if __name__ == "__main__":
    main()