File size: 2,413 Bytes
b36071f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Pack FastFrames-L transformer projections as groupwise affine Q8."""

import argparse
import os
from pathlib import Path
from tempfile import NamedTemporaryFile
from time import perf_counter

import mlx.core as mx


GROUP_SIZE = 64
BITS = 8
METADATA = {"format": "fastframes-l-affine", "bits": str(BITS), "group_size": str(GROUP_SIZE)}


def pack(source, destination):
    if destination.exists() or destination.is_symlink():
        raise FileExistsError(destination)
    mx.set_default_device(mx.gpu)
    mx.set_cache_limit(2 * 1024**3)
    started = perf_counter()
    weights = mx.load(str(source))
    if weights["patch_embedding.weight"].shape != (5120, 16, 1, 2, 2):
        raise ValueError("Le checkpoint ne correspond pas à FastFrames-L.")
    total = 0
    packed = {}
    for name in tuple(weights):
        tensor = weights.pop(name)
        if name.startswith("blocks.") and name.endswith(".weight") and tensor.ndim == 2:
            if tensor.dtype != mx.bfloat16 or tensor.shape[-1] % GROUP_SIZE:
                raise ValueError(f"Projection incompatible : {name}")
            quantized, scales, biases = mx.quantize(tensor, group_size=GROUP_SIZE, bits=BITS)
            mx.eval(quantized, scales, biases)
            prefix = name.removesuffix(".weight")
            packed.update({name: quantized, f"{prefix}.scales": scales, f"{prefix}.biases": biases})
            total += 1
            if total % 100 == 0:
                print(f"{total} matrices quantifiées", flush=True)
        else:
            packed[name] = tensor
    if total != 400:
        raise ValueError(f"Nombre de projections inattendu : {total}")

    with NamedTemporaryFile(dir=destination.parent, suffix=".safetensors", delete=False) as temp:
        pending = Path(temp.name)
    try:
        mx.save_safetensors(pending, packed, metadata=METADATA)
        os.link(pending, destination)
    finally:
        pending.unlink()
    print(f"{total} matrices · {destination.stat().st_size / 1e9:.2f} Go · "
          f"{perf_counter() - started:.1f} s", flush=True)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--weights", type=Path, default=Path(__file__).parent / "weights/fastframes-l")
    args = parser.parse_args()
    pack(args.weights / "dit.safetensors", args.weights / "dit-q8.safetensors")


if __name__ == "__main__":
    main()