weights.py 14.9 KB
Newer Older
Nicolas Patry's avatar
Nicolas Patry committed
1
import os
2
from pathlib import Path
3
from typing import List, Dict, Optional, Tuple
4
from safetensors import safe_open, SafetensorError
5
import torch
6
from loguru import logger
7
8
from huggingface_hub import hf_hub_download
import json
9
from text_generation_server.utils.log import log_once
10
11
12


class Weights:
13
14
15
16
17
18
19
    def __init__(
        self,
        filenames: List[Path],
        device,
        dtype,
        process_group,
        aliases: Optional[Dict[str, List[str]]] = None,
OlivierDehaene's avatar
OlivierDehaene committed
20
        prefix: Optional[str] = None,
21
    ):
22
23
24
25
26
27
28
29
30
        routing = {}
        for filename in filenames:
            with safe_open(filename, framework="pytorch") as f:
                for k in f.keys():
                    if k in routing:
                        raise RuntimeError(
                            f"Key {k} was found in multiple files: {filename} and {routing[k]}"
                        )
                    routing[k] = filename
31
32
33
        if aliases is None:
            aliases = {}
        self.aliases = aliases
34
35
36
37
        self.routing = routing
        self.device = device
        self.dtype = dtype
        self.process_group = process_group
Nicolas Patry's avatar
Nicolas Patry committed
38
        self.prefix = prefix
39
40
41
42
43
44
45
46
47
        self._handles = {}

    def _get_handle(self, filename):
        if filename not in self._handles:
            f = safe_open(filename, framework="pytorch")
            self._handles[filename] = f

        return self._handles[filename]

48
    def get_filename(self, tensor_name: str) -> (str, str):
Nicolas Patry's avatar
Nicolas Patry committed
49
50
51
52
53
54
55
56
57
58
59

        names = [tensor_name]
        if self.prefix is not None:
            prefixed = f"{self.prefix}.{tensor_name}"
            names.append(prefixed)
        for name in names:
            filename = self.routing.get(name, None)
            if filename is not None:
                return str(filename), name

            aliases = self.aliases.get(name, [])
60
61
62
63
            for alias in aliases:
                filename = self.routing.get(alias, None)
                if filename is not None:
                    return str(filename), alias
Nicolas Patry's avatar
Nicolas Patry committed
64
        raise RuntimeError(f"weight {tensor_name} does not exist")
65
66

    def _get_slice(self, tensor_name: str):
67
        filename, tensor_name = self.get_filename(tensor_name)
68
69
70
71
72
73
74
        f = self._get_handle(filename)
        slice_ = f.get_slice(tensor_name)
        return slice_

    def get_shape(self, tensor_name: str):
        return self._get_slice(tensor_name).get_shape()

OlivierDehaene's avatar
OlivierDehaene committed
75
    def get_tensor(self, tensor_name: str, to_device=True):
76
        filename, tensor_name = self.get_filename(tensor_name)
77
78
        f = self._get_handle(filename)
        tensor = f.get_tensor(tensor_name)
79
80
81
82
        # Special case for gptq which shouldn't convert
        # u4 which are disguised as int32
        if tensor.dtype not in [torch.int32, torch.int64]:
            tensor = tensor.to(dtype=self.dtype)
xiaobin's avatar
xiaobin committed
83
84
        if to_device:
            tensor = tensor.to(device=self.device)
85
86
        return tensor

87
    def get_partial_sharded(self, tensor_name: str, dim: int):
88
        filename, tensor_name = self.get_filename(tensor_name)
xiaobin's avatar
xiaobin committed
89
90
        f = self._get_handle(filename)
        slice_ = f.get_slice(tensor_name)
91
92
93
94
95
96
97
98
99
100
101
102
103
104
        world_size = self.process_group.size()
        rank = self.process_group.rank()

        size = slice_.get_shape()[dim]
        block_size = size // world_size
        start = rank * block_size
        stop = (rank + 1) * block_size

        if dim == 0:
            tensor = slice_[start:stop]
        elif dim == 1:
            tensor = slice_[:, start:stop]
        else:
            raise NotImplementedError("Let's make that generic when needed")
105
106
107
108
        # Special case for gptq which shouldn't convert
        # u4 which are disguised as int32
        if tensor.dtype != torch.int32:
            tensor = tensor.to(dtype=self.dtype)
109
110
        tensor = tensor.to(device=self.device)
        return tensor
111

112
113
114
115
116
117
118
119
120
121
122
    def get_sharded(self, tensor_name: str, dim: int):
        filename, tensor_name = self.get_filename(tensor_name)
        f = self._get_handle(filename)
        slice_ = f.get_slice(tensor_name)
        world_size = self.process_group.size()
        size = slice_.get_shape()[dim]
        assert (
            size % world_size == 0
        ), f"The choosen size {size} is not compatible with sharding on {world_size} shards"
        return self.get_partial_sharded(tensor_name, dim)

xiaobin's avatar
xiaobin committed
123
124
125
126
127
128
129
130
    def _get_qweight(self, name: str):
        slice_ = self._get_slice(name)
        total_size = slice_.get_shape()[1]
        assert total_size % 3 == 0, "Prepacked quantized qkv is not divisible by 3"
        single_size = total_size // 3
        world_size = self.process_group.size()
        rank = self.process_group.rank()

OlivierDehaene's avatar
OlivierDehaene committed
131
132
133
        assert (
            single_size % world_size == 0
        ), f"Prepacked quantized qkv cannot be sharded across {world_size} shards"
xiaobin's avatar
xiaobin committed
134
135
136
137
        block_size = single_size // world_size
        start = rank * block_size
        stop = (rank + 1) * block_size
        q = slice_[:, start:stop]
OlivierDehaene's avatar
OlivierDehaene committed
138
139
140
        k = slice_[:, start + single_size : stop + single_size]
        v = slice_[:, start + 2 * single_size : stop + 2 * single_size]
        weight = torch.cat([q, k, v], dim=1)
xiaobin's avatar
xiaobin committed
141
142
143
144
145
146
147
148
        weight = weight.to(device=self.device)
        return weight

    def get_weights_col_packed_qkv(self, prefix: str, quantize: str):
        """
        Highly specific when the underlying tensor is a simple cat of Q,K,V instead of being
        already alternating Q,K,V within the main tensor
        """
149
        if quantize in ["gptq", "awq"]:
xiaobin's avatar
xiaobin committed
150
            try:
OlivierDehaene's avatar
OlivierDehaene committed
151
                qweight = self._get_qweight(f"{prefix}.qweight")
xiaobin's avatar
xiaobin committed
152
153
            except RuntimeError:
                raise RuntimeError(
154
                    f"Cannot load `{quantize}` weight, make sure the model is already quantized."
xiaobin's avatar
xiaobin committed
155
156
                )

OlivierDehaene's avatar
OlivierDehaene committed
157
158
            qzeros = self._get_qweight(f"{prefix}.qzeros")
            scales = self._get_qweight(f"{prefix}.scales")
xiaobin's avatar
xiaobin committed
159
            scales = scales.to(dtype=self.dtype)
160
161
162
163
            if quantize == "gptq":
                g_idx = self.get_tensor(f"{prefix}.g_idx")
            else:
                g_idx = None
xiaobin's avatar
xiaobin committed
164

165
            bits, groupsize, _ = self._get_gptq_params()
xiaobin's avatar
xiaobin committed
166
167
            weight = (qweight, qzeros, scales, g_idx, bits, groupsize, False)
        else:
OlivierDehaene's avatar
OlivierDehaene committed
168
            slice_ = self._get_slice(f"{prefix}.weight")
xiaobin's avatar
xiaobin committed
169
170
171
172
173
174
            total_size = slice_.get_shape()[0]
            assert total_size % 3 == 0, "Prepacked qkv is not divisible by 3"
            single_size = total_size // 3
            world_size = self.process_group.size()
            rank = self.process_group.rank()

OlivierDehaene's avatar
OlivierDehaene committed
175
176
177
            assert (
                single_size % world_size == 0
            ), f"Prepacked qkv cannot be sharded across {world_size} shards"
xiaobin's avatar
xiaobin committed
178
179
180
181
            block_size = single_size // world_size
            start = rank * block_size
            stop = (rank + 1) * block_size
            q = slice_[start:stop]
OlivierDehaene's avatar
OlivierDehaene committed
182
183
184
            k = slice_[start + single_size : stop + single_size]
            v = slice_[start + 2 * single_size : stop + 2 * single_size]
            weight = torch.cat([q, k, v], dim=0)
xiaobin's avatar
xiaobin committed
185
186
187
188
            weight = weight.to(device=self.device)
            weight = weight.to(dtype=self.dtype)
        return weight

189
    def get_multi_weights_col(self, prefixes: List[str], quantize: str, dim: int):
190
        if quantize in ["gptq", "awq"]:
191
            try:
192
193
194
                qweight = torch.cat(
                    [self.get_sharded(f"{p}.qweight", dim=1) for p in prefixes], dim=1
                )
195
            except RuntimeError:
196
                raise RuntimeError(
197
                    f"Cannot load `{quantize}` weight, make sure the model is already quantized"
198
199
200
201
202
203
204
205
                )

            qzeros = torch.cat(
                [self.get_sharded(f"{p}.qzeros", dim=1) for p in prefixes], dim=1
            )
            scales = torch.cat(
                [self.get_sharded(f"{p}.scales", dim=1) for p in prefixes], dim=1
            )
206
207
208
209
210
211
212
213

            if quantize == "gptq":
                w = [self.get_tensor(f"{p}.g_idx") for p in prefixes]
                for w2 in w[1:]:
                    torch.testing.assert_close(w2, w[0])
                g_idx = w[0]
            else:
                g_idx = None
214

215
            bits, groupsize, desc_act = self._get_gptq_params()
216
            from text_generation_server.utils.layers import HAS_EXLLAMA
OlivierDehaene's avatar
OlivierDehaene committed
217

OlivierDehaene's avatar
v1.3.4  
OlivierDehaene committed
218
219
220
            use_exllama = (
                bits == 4 and HAS_EXLLAMA and quantize == "gptq" and not desc_act
            )
221
            weight = (qweight, qzeros, scales, g_idx, bits, groupsize, use_exllama)
222
223
224
225
        else:
            w = [self.get_sharded(f"{p}.weight", dim=0) for p in prefixes]
            weight = torch.cat(w, dim=dim)
        return weight
OlivierDehaene's avatar
OlivierDehaene committed
226

xiaobin's avatar
xiaobin committed
227
228
229
230
231
232
233
234
235
236
237
238
239
240
    def get_tensor_shard(self, var, dim):
        world_size = self.process_group.size()
        rank = self.process_group.rank()
        block_size = var.size()[dim] // world_size
        start = rank * block_size
        stop = (rank + 1) * block_size
        if dim == 0:
            tensor = var[start:stop]
        elif dim == 1:
            tensor = var[:, start:stop]
        else:
            raise NotImplementedError("Let's make that generic when needed")
        tensor = tensor.to(dtype=self.dtype)
        tensor = tensor.to(device=self.device)
OlivierDehaene's avatar
OlivierDehaene committed
241
        return tensor
242
243
244

    def get_multi_weights_row(self, prefix: str, quantize: str):
        if quantize == "gptq":
245
            use_exllama = True
246
            bits, groupsize, desc_act = self._get_gptq_params()
247
248
249
250

            if bits != 4:
                use_exllama = False

251
252
253
254
            if desc_act:
                log_once(logger.warning, "Disabling exllama because desc_act=True")
                use_exllama = False

255
256
257
            if self.process_group.size() > 1:
                g_idx = self.get_tensor(f"{prefix}.g_idx")
                if g_idx is not None:
258
259
260
261
262
263
264
265
266
267
                    if (
                        not torch.equal(
                            g_idx.cpu(),
                            torch.tensor(
                                [i // groupsize for i in range(g_idx.shape[0])],
                                dtype=torch.int32,
                            ),
                        )
                        and not (g_idx == 0).all()
                    ):
268
269
270
271
                        # Exllama implementation does not support row tensor parallelism with act-order, as
                        # it would require to reorder input activations that are split unto several GPUs
                        use_exllama = False

272
273
274
            try:
                qweight = self.get_sharded(f"{prefix}.qweight", dim=0)
            except RuntimeError:
275
276
277
                raise RuntimeError(
                    "Cannot load `gptq` weight, make sure the model is already quantized, or quantize it with `text-generation-server quantize ORIGINAL_MODEL_ID NEW_MODEL_ID`"
                )
278

279
            from text_generation_server.utils.layers import HAS_EXLLAMA, CAN_EXLLAMA
280

281
            if use_exllama:
282
283
                if not HAS_EXLLAMA:
                    if CAN_EXLLAMA:
284
285
                        log_once(
                            logger.warning,
OlivierDehaene's avatar
v1.3.4  
OlivierDehaene committed
286
                            "Exllama GPTQ cuda kernels (which are faster) could have been used, but are not currently installed, try using BUILD_EXTENSIONS=True",
287
                        )
288
289
                    use_exllama = False
                else:
OlivierDehaene's avatar
v1.3.4  
OlivierDehaene committed
290
                    log_once(logger.info, f"Using exllama kernels v{HAS_EXLLAMA}")
291
292

            g_idx = self.get_sharded(f"{prefix}.g_idx", dim=0)
293

294
            if use_exllama and groupsize != -1:
Nicolas Patry's avatar
Nicolas Patry committed
295
296
                qzeros = self.get_sharded(f"{prefix}.qzeros", dim=0)
                scales = self.get_sharded(f"{prefix}.scales", dim=0)
297
298
299
            else:
                qzeros = self.get_tensor(f"{prefix}.qzeros")
                scales = self.get_tensor(f"{prefix}.scales")
300
301
302

            if use_exllama:
                g_idx = g_idx - g_idx[0]
303

304
305
            weight = (qweight, qzeros, scales, g_idx, bits, groupsize, use_exllama)
        elif quantize == "awq":
306
            bits, groupsize, _ = self._get_gptq_params()
307
308
309
310
311
312
313
314
315
316
317
318

            try:
                qweight = self.get_sharded(f"{prefix}.qweight", dim=0)
            except RuntimeError:
                raise RuntimeError(
                    "Cannot load `awq` weight, make sure the model is already quantized"
                )

            qzeros = self.get_sharded(f"{prefix}.qzeros", dim=0)
            scales = self.get_sharded(f"{prefix}.scales", dim=0)
            g_idx = None
            use_exllama = False
OlivierDehaene's avatar
OlivierDehaene committed
319

320
            weight = (qweight, qzeros, scales, g_idx, bits, groupsize, use_exllama)
321
322
323
        else:
            weight = self.get_sharded(f"{prefix}.weight", dim=1)
        return weight
324

325
    def _get_gptq_params(self) -> Tuple[int, int, int]:
326
327
328
        try:
            bits = self.get_tensor("gptq_bits").item()
            groupsize = self.get_tensor("gptq_groupsize").item()
329
            desc_act = False
330
331
        except (SafetensorError, RuntimeError) as e:
            try:
332
333
                bits = self.gptq_bits
                groupsize = self.gptq_groupsize
334
                desc_act = getattr(self, "gptq_desc_act", False)
335
336
337
            except Exception:
                raise e

338
        return bits, groupsize, desc_act
339

OlivierDehaene's avatar
OlivierDehaene committed
340
    def _set_gptq_params(self, model_id, revision):
341
        filename = "config.json"
342
        try:
343
            if os.path.exists(os.path.join(model_id, filename)):
Nicolas Patry's avatar
Nicolas Patry committed
344
345
                filename = os.path.join(model_id, filename)
            else:
OlivierDehaene's avatar
OlivierDehaene committed
346
347
348
                filename = hf_hub_download(
                    model_id, filename=filename, revision=revision
                )
349
350
            with open(filename, "r") as f:
                data = json.load(f)
351
352
            self.gptq_bits = data["quantization_config"]["bits"]
            self.gptq_groupsize = data["quantization_config"]["group_size"]
353
            self.gptq_desc_act = data["quantization_config"]["desc_act"]
354
        except Exception:
355
356
357
358
359
            filename = "quantize_config.json"
            try:
                if os.path.exists(os.path.join(model_id, filename)):
                    filename = os.path.join(model_id, filename)
                else:
OlivierDehaene's avatar
OlivierDehaene committed
360
361
362
                    filename = hf_hub_download(
                        model_id, filename=filename, revision=revision
                    )
363
364
365
366
                with open(filename, "r") as f:
                    data = json.load(f)
                self.gptq_bits = data["bits"]
                self.gptq_groupsize = data["group_size"]
367
                self.gptq_desc_act = data["desc_act"]
368
            except Exception:
369
370
371
372
373
                filename = "quant_config.json"
                try:
                    if os.path.exists(os.path.join(model_id, filename)):
                        filename = os.path.join(model_id, filename)
                    else:
OlivierDehaene's avatar
OlivierDehaene committed
374
375
376
                        filename = hf_hub_download(
                            model_id, filename=filename, revision=revision
                        )
377
378
379
380
                    with open(filename, "r") as f:
                        data = json.load(f)
                    self.gptq_bits = data["w_bit"]
                    self.gptq_groupsize = data["q_group_size"]
381
                    self.gptq_desc_act = data["desc_act"]
382
383
                except Exception:
                    pass