kv_qparams.py 3.96 KB
Newer Older
1
2
# Copyright (c) OpenMMLab. All rights reserved.
from pathlib import Path
pppppM's avatar
pppppM committed
3
from typing import Union
4
5

import fire
pppppM's avatar
pppppM committed
6
import numpy as np
7
8
9
import torch


pppppM's avatar
pppppM committed
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
def _export_sym(key_stats: dict,
                value_stats: dict,
                bits: int,
                out_dir: Union[str, Path],
                tp: int = 1) -> None:
    """Export symmetric quantization parameters to specified directory."""
    keys_absmax = key_stats['absmax']
    values_absmax = value_stats['absmax']
    for layer_idx, name in enumerate(keys_absmax.keys()):
        k_absmax = keys_absmax[name]
        v_absmax = values_absmax[name]

        heads, dims = k_absmax.shape
        assert heads % tp == 0

        mp_k_absmax = torch.chunk(k_absmax, tp)
        mp_v_absmax = torch.chunk(v_absmax, tp)
        for i in range(tp):
            # quant: q = f / scale
            # dequant: f = q * scale
            k_s = mp_k_absmax[i].max() / (2**(bits - 1) - 1)
            v_s = mp_v_absmax[i].max() / (2**(bits - 1) - 1)

            kv_qparams = np.array([k_s, v_s], dtype=np.float32)
            out_path = out_dir / f'layers.{layer_idx}.past_kv_scale.{i}.weight'  # noqa: E501
            kv_qparams.tofile(out_path)
            print(f'Layer {layer_idx} MP {i} KV scales done.')


def _export_asym(key_stats: dict,
                 value_stats: dict,
                 bits: int,
                 out_dir: Union[str, Path],
                 tp: int = 1) -> None:
    """Export asymmetric quantization parameters to specified directory."""
    keys_min = key_stats['min']
    values_min = value_stats['min']

    keys_max = key_stats['max']
    values_max = value_stats['max']
    for layer_idx, name in enumerate(keys_min.keys()):
        k_max = keys_max[name]
        v_max = values_max[name]

        k_min = keys_min[name]
        v_min = values_min[name]

        heads, dims = k_min.shape
        assert heads % tp == 0

        tp_k_min = torch.chunk(k_min, tp)
        tp_v_min = torch.chunk(v_min, tp)

        tp_k_max = torch.chunk(k_max, tp)
        tp_v_max = torch.chunk(v_max, tp)
        for i in range(tp):
66
67
68
            # zp = (min+max) / 2
            # scale = (max-min) / 255
            # quant: q = (f-zp) / scale
pppppM's avatar
pppppM committed
69
70
71
            # dequant: f = q * scale + zp
            k_min = tp_k_min[i].min()
            v_min = tp_v_min[i].min()
72

pppppM's avatar
pppppM committed
73
74
            k_max = tp_k_max[i].max()
            v_max = tp_v_max[i].max()
75

pppppM's avatar
pppppM committed
76
77
            k_scale = (k_max - k_min) / (2**bits - 1)
            v_scale = (v_max - v_min) / (2**bits - 1)
78

79
80
81
82
            k_zp = (k_max + k_min) / 2
            v_zp = (v_max + v_min) / 2

            kv_qparams = np.array([k_scale, k_zp, v_scale, v_zp],
pppppM's avatar
pppppM committed
83
84
85
86
                                  dtype=np.float32)
            out_path = out_dir / f'layers.{layer_idx}.past_kv_scale.{i}.weight'  # noqa: E501
            kv_qparams.tofile(out_path)
            print(f'Layer {layer_idx} MP {i} KV scales&zeros done.')
87
88


pppppM's avatar
pppppM committed
89
90
91
92
93
94
def main(work_dir: str,
         turbomind_dir: str,
         kv_bits: int = 8,
         kv_sym: bool = True,
         num_tp: int = 1) -> None:
    """Main function to export key and value stats.
95
96

    Args:
pppppM's avatar
pppppM committed
97
98
99
100
101
102
103
104
        work_dir (Union[str, Path]): Directory path where the stats are saved.
        turbomind_dir (Union[str, Path]): Directory path where to
            save the results.
        kv_bits (int, optional): Number of bits for quantization.
            Defaults to 8.
        kv_sym (bool, optional): Whether to use symmetric quantizaiton.
            Defaults to True.
        num_tp (int, optional): Number of tensor parallelism. Defaults to 1.
105
106
    """

pppppM's avatar
pppppM committed
107
    work_dir = Path(work_dir)
108

pppppM's avatar
pppppM committed
109
110
    tm_dir = Path(turbomind_dir)
    assert tm_dir.exists(), 'The specified TurboMind directory does not exist.'
111

pppppM's avatar
pppppM committed
112
113
    key_stats = torch.load(work_dir / 'key_stats.pth')
    value_stats = torch.load(work_dir / 'value_stats.pth')
114

pppppM's avatar
pppppM committed
115
116
117
118
    if kv_sym:
        _export_sym(key_stats, value_stats, kv_bits, tm_dir, num_tp)
    else:
        _export_asym(key_stats, value_stats, kv_bits, tm_dir, num_tp)
119
120
121
122
123


if __name__ == '__main__':

    fire.Fire(main)