weights.py 17.6 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
        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, [])
59
60
61
62
            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
63
        raise RuntimeError(f"weight {tensor_name} does not exist")
64
65

    def _get_slice(self, tensor_name: str):
66
        filename, tensor_name = self.get_filename(tensor_name)
67
68
69
70
71
72
73
        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
74
    def get_tensor(self, tensor_name: str, to_device=True):
75
        filename, tensor_name = self.get_filename(tensor_name)
76
77
        f = self._get_handle(filename)
        tensor = f.get_tensor(tensor_name)
78
79
80
81
        # 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
82
83
        if to_device:
            tensor = tensor.to(device=self.device)
84
85
        return tensor

86
    def get_partial_sharded(self, tensor_name: str, dim: int):
87
        filename, tensor_name = self.get_filename(tensor_name)
xiaobin's avatar
xiaobin committed
88
89
        f = self._get_handle(filename)
        slice_ = f.get_slice(tensor_name)
90
91
92
93
        world_size = self.process_group.size()
        rank = self.process_group.rank()

        size = slice_.get_shape()[dim]
94
        block_size = (size + world_size - 1) // world_size
95
96
97
98
99
100
101
102
103
        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")
104
105
106
107
        # 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)
108
109
        tensor = tensor.to(device=self.device)
        return tensor
110

111
112
113
114
115
116
117
118
119
120
121
    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
122
123
124
125
126
127
128
129
    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
130
131
132
        assert (
            single_size % world_size == 0
        ), f"Prepacked quantized qkv cannot be sharded across {world_size} shards"
xiaobin's avatar
xiaobin committed
133
134
135
136
        block_size = single_size // world_size
        start = rank * block_size
        stop = (rank + 1) * block_size
        q = slice_[:, start:stop]
OlivierDehaene's avatar
OlivierDehaene committed
137
138
139
        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
140
141
142
143
144
145
146
147
        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
        """
148
        if quantize in ["gptq", "awq"]:
xiaobin's avatar
xiaobin committed
149
            try:
OlivierDehaene's avatar
OlivierDehaene committed
150
                qweight = self._get_qweight(f"{prefix}.qweight")
xiaobin's avatar
xiaobin committed
151
152
            except RuntimeError:
                raise RuntimeError(
153
                    f"Cannot load `{quantize}` weight, make sure the model is already quantized."
xiaobin's avatar
xiaobin committed
154
155
                )

Ilyas Moutawwakil's avatar
Ilyas Moutawwakil committed
156
157
            bits, groupsize, _, quant_method = self._get_gptq_params()

OlivierDehaene's avatar
OlivierDehaene committed
158
159
            qzeros = self._get_qweight(f"{prefix}.qzeros")
            scales = self._get_qweight(f"{prefix}.scales")
xiaobin's avatar
xiaobin committed
160
            scales = scales.to(dtype=self.dtype)
Ilyas Moutawwakil's avatar
Ilyas Moutawwakil committed
161
162

            if quantize == "gptq" and quant_method == "gptq":
163
                g_idx = self.get_tensor(f"{prefix}.g_idx")
Ilyas Moutawwakil's avatar
Ilyas Moutawwakil committed
164
165
166
167
168
169
170
171
172
173
174
175
176
            elif quantize == "gptq" and quant_method == "awq":
                log_once(
                    logger.info, "Converting AWQ model to Exllama/GPTQ packing format."
                )
                from text_generation_server.utils.awq.conversion_utils import (
                    fast_awq_to_gptq,
                )

                qweight, qzeros = fast_awq_to_gptq(qweight, qzeros)
                g_idx = (
                    torch.arange(qweight.shape[0] * (32 // bits), device=qweight.device)
                    // groupsize
                ).to(dtype=torch.int32)
177
178
            else:
                g_idx = None
xiaobin's avatar
xiaobin committed
179
180
181

            weight = (qweight, qzeros, scales, g_idx, bits, groupsize, False)
        else:
OlivierDehaene's avatar
OlivierDehaene committed
182
            slice_ = self._get_slice(f"{prefix}.weight")
xiaobin's avatar
xiaobin committed
183
184
185
186
187
188
            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
189
190
191
            assert (
                single_size % world_size == 0
            ), f"Prepacked qkv cannot be sharded across {world_size} shards"
xiaobin's avatar
xiaobin committed
192
193
194
195
            block_size = single_size // world_size
            start = rank * block_size
            stop = (rank + 1) * block_size
            q = slice_[start:stop]
OlivierDehaene's avatar
OlivierDehaene committed
196
197
198
            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
199
200
201
202
            weight = weight.to(device=self.device)
            weight = weight.to(dtype=self.dtype)
        return weight

203
    def get_multi_weights_col(self, prefixes: List[str], quantize: str, dim: int):
204
        if quantize in ["gptq", "awq"]:
205
            try:
206
207
208
                qweight = torch.cat(
                    [self.get_sharded(f"{p}.qweight", dim=1) for p in prefixes], dim=1
                )
209
            except RuntimeError:
210
                raise RuntimeError(
211
                    f"Cannot load `{quantize}` weight, make sure the model is already quantized"
212
213
214
215
216
217
218
219
                )

            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
            )
220

Ilyas Moutawwakil's avatar
Ilyas Moutawwakil committed
221
222
223
224
225
226
227
228
229
            bits, groupsize, desc_act, quant_method = self._get_gptq_params()

            from text_generation_server.utils.layers import HAS_EXLLAMA

            use_exllama = (
                bits == 4 and HAS_EXLLAMA and quantize == "gptq" and not desc_act
            )

            if quantize == "gptq" and quant_method == "gptq":
230
231
232
233
                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]
Ilyas Moutawwakil's avatar
Ilyas Moutawwakil committed
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
            elif quantize == "gptq" and quant_method == "awq":
                log_once(
                    logger.info, "Converting AWQ model to Exllama/GPTQ packing format."
                )
                from text_generation_server.utils.awq.conversion_utils import (
                    fast_awq_to_gptq,
                )

                qweight, qzeros = fast_awq_to_gptq(qweight, qzeros)
                if use_exllama:
                    g_idx = None
                else:
                    g_idx = (
                        torch.arange(
                            qweight.shape[0] * (32 // bits), device=qweight.device
                        )
                        // groupsize
                    ).to(dtype=torch.int32)
252
253
            else:
                g_idx = None
254

255
            weight = (qweight, qzeros, scales, g_idx, bits, groupsize, use_exllama)
256
257
258
259
        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
260

xiaobin's avatar
xiaobin committed
261
262
263
264
265
266
267
268
269
270
271
272
273
274
    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
275
        return tensor
276
277
278

    def get_multi_weights_row(self, prefix: str, quantize: str):
        if quantize == "gptq":
279
            use_exllama = True
Ilyas Moutawwakil's avatar
Ilyas Moutawwakil committed
280
            bits, groupsize, desc_act, quant_method = self._get_gptq_params()
281
282
283
284

            if bits != 4:
                use_exllama = False

285
286
287
288
            if desc_act:
                log_once(logger.warning, "Disabling exllama because desc_act=True")
                use_exllama = False

Ilyas Moutawwakil's avatar
Ilyas Moutawwakil committed
289
290
291
292
293
294
295
296
297
298
299
300
            try:
                qweight = self.get_sharded(f"{prefix}.qweight", dim=0)
            except RuntimeError:
                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`"
                )

            if quant_method == "gptq":
                g_idx = self.get_sharded(f"{prefix}.g_idx", dim=0)
            elif quant_method == "awq":
                g_idx = None

301
302
            if self.process_group.size() > 1:
                if g_idx is not None:
303
304
305
306
307
308
309
310
311
312
                    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()
                    ):
313
314
315
316
                        # 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

317
            from text_generation_server.utils.layers import HAS_EXLLAMA, CAN_EXLLAMA
318

319
            if use_exllama:
320
321
                if not HAS_EXLLAMA:
                    if CAN_EXLLAMA:
322
323
                        log_once(
                            logger.warning,
OlivierDehaene's avatar
v1.3.4  
OlivierDehaene committed
324
                            "Exllama GPTQ cuda kernels (which are faster) could have been used, but are not currently installed, try using BUILD_EXTENSIONS=True",
325
                        )
326
327
                    use_exllama = False
                else:
OlivierDehaene's avatar
v1.3.4  
OlivierDehaene committed
328
                    log_once(logger.info, f"Using exllama kernels v{HAS_EXLLAMA}")
329

330
            if use_exllama and groupsize != -1:
Nicolas Patry's avatar
Nicolas Patry committed
331
332
                qzeros = self.get_sharded(f"{prefix}.qzeros", dim=0)
                scales = self.get_sharded(f"{prefix}.scales", dim=0)
333
334
335
            else:
                qzeros = self.get_tensor(f"{prefix}.qzeros")
                scales = self.get_tensor(f"{prefix}.scales")
336

Ilyas Moutawwakil's avatar
Ilyas Moutawwakil committed
337
            if use_exllama and g_idx is not None:
338
                g_idx = g_idx - g_idx[0]
339

Ilyas Moutawwakil's avatar
Ilyas Moutawwakil committed
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
            if quant_method == "awq":
                log_once(
                    logger.info, "Converting AWQ model to Exllama/GPTQ packing format."
                )
                from text_generation_server.utils.awq.conversion_utils import (
                    fast_awq_to_gptq,
                )

                qweight, qzeros = fast_awq_to_gptq(qweight, qzeros)
                if use_exllama:
                    g_idx = None
                else:
                    g_idx = (
                        torch.arange(
                            qweight.shape[0] * (32 // bits), device=qweight.device
                        )
                        // groupsize
                    ).to(dtype=torch.int32)

359
360
            weight = (qweight, qzeros, scales, g_idx, bits, groupsize, use_exllama)
        elif quantize == "awq":
Ilyas Moutawwakil's avatar
Ilyas Moutawwakil committed
361
            bits, groupsize, _, _ = self._get_gptq_params()
362
363
364
365
366
367
368
369
370
371
372
373

            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
374

375
            weight = (qweight, qzeros, scales, g_idx, bits, groupsize, use_exllama)
376
377
378
        else:
            weight = self.get_sharded(f"{prefix}.weight", dim=1)
        return weight
379

Ilyas Moutawwakil's avatar
Ilyas Moutawwakil committed
380
    def _get_gptq_params(self) -> Tuple[int, int, int, str]:
381
382
383
        try:
            bits = self.get_tensor("gptq_bits").item()
            groupsize = self.get_tensor("gptq_groupsize").item()
384
            desc_act = False
Ilyas Moutawwakil's avatar
Ilyas Moutawwakil committed
385
            quant_method = "gptq"
386
387
        except (SafetensorError, RuntimeError) as e:
            try:
388
389
                bits = self.gptq_bits
                groupsize = self.gptq_groupsize
390
                desc_act = getattr(self, "gptq_desc_act", False)
Ilyas Moutawwakil's avatar
Ilyas Moutawwakil committed
391
                quant_method = getattr(self, "quant_method", "gptq")
392
393
394
            except Exception:
                raise e

Ilyas Moutawwakil's avatar
Ilyas Moutawwakil committed
395
        return bits, groupsize, desc_act, quant_method
396

OlivierDehaene's avatar
OlivierDehaene committed
397
    def _set_gptq_params(self, model_id, revision):
398
        filename = "config.json"
399
        try:
400
            if os.path.exists(os.path.join(model_id, filename)):
Nicolas Patry's avatar
Nicolas Patry committed
401
402
                filename = os.path.join(model_id, filename)
            else:
OlivierDehaene's avatar
OlivierDehaene committed
403
404
405
                filename = hf_hub_download(
                    model_id, filename=filename, revision=revision
                )
406
407
            with open(filename, "r") as f:
                data = json.load(f)
408
409
            self.gptq_bits = data["quantization_config"]["bits"]
            self.gptq_groupsize = data["quantization_config"]["group_size"]
410
            # Order is important here, desc_act is missing on some real models
Ilyas Moutawwakil's avatar
Ilyas Moutawwakil committed
411
            self.quant_method = data["quantization_config"]["quant_method"]
412
            self.gptq_desc_act = data["quantization_config"]["desc_act"]
413
        except Exception:
414
415
416
417
418
            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
419
420
421
                    filename = hf_hub_download(
                        model_id, filename=filename, revision=revision
                    )
422
423
424
425
                with open(filename, "r") as f:
                    data = json.load(f)
                self.gptq_bits = data["bits"]
                self.gptq_groupsize = data["group_size"]
426
                self.gptq_desc_act = data["desc_act"]
Ilyas Moutawwakil's avatar
Ilyas Moutawwakil committed
427
428
                if "version" in data and data["version"] == "GEMM":
                    self.quant_method = "awq"
429
            except Exception:
430
431
432
433
434
                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
435
436
437
                        filename = hf_hub_download(
                            model_id, filename=filename, revision=revision
                        )
438
439
440
441
                    with open(filename, "r") as f:
                        data = json.load(f)
                    self.gptq_bits = data["w_bit"]
                    self.gptq_groupsize = data["q_group_size"]
442
                    self.gptq_desc_act = data["desc_act"]
Ilyas Moutawwakil's avatar
Ilyas Moutawwakil committed
443
444
                    if "version" in data and data["version"] == "GEMM":
                        self.quant_method = "awq"
445
446
                except Exception:
                    pass