compressed-tensors 0.3.2__py3-none-any.whl → 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- compressed_tensors/base.py +2 -1
- compressed_tensors/compressors/__init__.py +5 -1
- compressed_tensors/compressors/base.py +11 -54
- compressed_tensors/compressors/dense.py +4 -4
- compressed_tensors/compressors/helpers.py +12 -12
- compressed_tensors/compressors/int_quantized.py +126 -0
- compressed_tensors/compressors/marlin_24.py +250 -0
- compressed_tensors/compressors/model_compressor.py +315 -0
- compressed_tensors/compressors/pack_quantized.py +212 -0
- compressed_tensors/compressors/sparse_bitmask.py +4 -4
- compressed_tensors/compressors/utils/__init__.py +19 -0
- compressed_tensors/compressors/utils/helpers.py +43 -0
- compressed_tensors/compressors/utils/permutations_24.py +65 -0
- compressed_tensors/compressors/utils/semi_structured_conversions.py +341 -0
- compressed_tensors/config/base.py +7 -4
- compressed_tensors/config/dense.py +4 -4
- compressed_tensors/config/sparse_bitmask.py +3 -3
- compressed_tensors/quantization/lifecycle/__init__.py +1 -0
- compressed_tensors/quantization/lifecycle/apply.py +75 -19
- compressed_tensors/quantization/lifecycle/compressed.py +69 -0
- compressed_tensors/quantization/lifecycle/forward.py +208 -22
- compressed_tensors/quantization/lifecycle/frozen.py +4 -0
- compressed_tensors/quantization/lifecycle/initialize.py +33 -5
- compressed_tensors/quantization/observers/base.py +70 -5
- compressed_tensors/quantization/observers/helpers.py +6 -1
- compressed_tensors/quantization/observers/memoryless.py +17 -9
- compressed_tensors/quantization/observers/min_max.py +44 -13
- compressed_tensors/quantization/quant_args.py +33 -4
- compressed_tensors/quantization/quant_config.py +69 -21
- compressed_tensors/quantization/quant_scheme.py +81 -1
- compressed_tensors/quantization/utils/helpers.py +77 -8
- compressed_tensors/utils/helpers.py +26 -122
- compressed_tensors/utils/safetensors_load.py +3 -2
- compressed_tensors/version.py +53 -0
- {compressed_tensors-0.3.2.dist-info → compressed_tensors-0.4.0.dist-info}/METADATA +46 -9
- compressed_tensors-0.4.0.dist-info/RECORD +48 -0
- compressed_tensors-0.3.2.dist-info/RECORD +0 -38
- {compressed_tensors-0.3.2.dist-info → compressed_tensors-0.4.0.dist-info}/LICENSE +0 -0
- {compressed_tensors-0.3.2.dist-info → compressed_tensors-0.4.0.dist-info}/WHEEL +0 -0
- {compressed_tensors-0.3.2.dist-info → compressed_tensors-0.4.0.dist-info}/top_level.txt +0 -0
compressed_tensors/base.py
CHANGED
@@ -14,7 +14,11 @@
|
|
14
14
|
|
15
15
|
# flake8: noqa
|
16
16
|
|
17
|
-
from .base import
|
17
|
+
from .base import Compressor
|
18
18
|
from .dense import DenseCompressor
|
19
19
|
from .helpers import load_compressed, save_compressed, save_compressed_model
|
20
|
+
from .int_quantized import IntQuantizationCompressor
|
21
|
+
from .marlin_24 import Marlin24Compressor
|
22
|
+
from .model_compressor import ModelCompressor, map_modules_to_quant_args
|
23
|
+
from .pack_quantized import PackedQuantizationCompressor
|
20
24
|
from .sparse_bitmask import BitmaskCompressor, BitmaskTensor
|
@@ -12,56 +12,30 @@
|
|
12
12
|
# See the License for the specific language governing permissions and
|
13
13
|
# limitations under the License.
|
14
14
|
|
15
|
-
import
|
16
|
-
from typing import Dict, Generator, Optional, Tuple
|
15
|
+
from typing import Dict, Generator, Tuple, Union
|
17
16
|
|
18
|
-
from compressed_tensors.
|
19
|
-
from compressed_tensors.
|
17
|
+
from compressed_tensors.config import SparsityCompressionConfig
|
18
|
+
from compressed_tensors.quantization import QuantizationConfig
|
20
19
|
from compressed_tensors.registry import RegistryMixin
|
21
|
-
from compressed_tensors.utils import get_safetensors_folder
|
22
20
|
from torch import Tensor
|
23
|
-
from torch.nn import Module, Parameter
|
24
|
-
from tqdm import tqdm
|
25
|
-
from transformers import AutoConfig
|
26
21
|
|
27
22
|
|
28
|
-
__all__ = ["
|
23
|
+
__all__ = ["Compressor"]
|
29
24
|
|
30
25
|
|
31
|
-
class
|
26
|
+
class Compressor(RegistryMixin):
|
32
27
|
"""
|
33
|
-
Base class representing a model compression algorithm
|
28
|
+
Base class representing a model compression algorithm
|
34
29
|
|
35
30
|
:param config: config specifying compression parameters
|
36
31
|
"""
|
37
32
|
|
38
|
-
|
39
|
-
|
40
|
-
|
41
|
-
) -> Optional["ModelCompressor"]:
|
42
|
-
"""
|
43
|
-
Given a path to a model config, extract a sparsity config if it exists and
|
44
|
-
return the associated ModelCompressor
|
45
|
-
|
46
|
-
:param pretrained_model_name_or_path: path to model config on disk or HF hub
|
47
|
-
:return: matching compressor if config contains a sparsity config
|
48
|
-
"""
|
49
|
-
config = AutoConfig.from_pretrained(pretrained_model_name_or_path)
|
50
|
-
sparsity_config = getattr(config, SPARSITY_CONFIG_NAME, None)
|
51
|
-
if sparsity_config is None:
|
52
|
-
return None
|
53
|
-
|
54
|
-
format = sparsity_config.get("format")
|
55
|
-
sparsity_config = CompressionConfig.load_from_registry(
|
56
|
-
format, **sparsity_config
|
57
|
-
)
|
58
|
-
compressor = cls.load_from_registry(format, config=sparsity_config)
|
59
|
-
return compressor
|
60
|
-
|
61
|
-
def __init__(self, config: Optional[CompressionConfig] = None):
|
33
|
+
def __init__(
|
34
|
+
self, config: Union[SparsityCompressionConfig, QuantizationConfig, None] = None
|
35
|
+
):
|
62
36
|
self.config = config
|
63
37
|
|
64
|
-
def compress(self, model_state: Dict[str, Tensor]) -> Dict[str, Tensor]:
|
38
|
+
def compress(self, model_state: Dict[str, Tensor], **kwargs) -> Dict[str, Tensor]:
|
65
39
|
"""
|
66
40
|
Compresses a dense state dict
|
67
41
|
|
@@ -80,24 +54,7 @@ class ModelCompressor(RegistryMixin):
|
|
80
54
|
|
81
55
|
:param model_path: path to compressed safetensors model (directory with
|
82
56
|
one or more safetensors files) or compressed tensors file
|
57
|
+
:param device: optional device to load intermediate weights into
|
83
58
|
:return: compressed state dict
|
84
59
|
"""
|
85
60
|
raise NotImplementedError()
|
86
|
-
|
87
|
-
def overwrite_weights(self, model_path: str, model: Module):
|
88
|
-
"""
|
89
|
-
Overwrites the weights in model with weights decompressed from model_path
|
90
|
-
|
91
|
-
:param model_path: path to compressed weights
|
92
|
-
:param model: pytorch model to load decompressed weights into
|
93
|
-
"""
|
94
|
-
model_path = get_safetensors_folder(model_path)
|
95
|
-
dense_gen = self.decompress(model_path)
|
96
|
-
for name, data in tqdm(dense_gen, desc="Decompressing model"):
|
97
|
-
# loading the decompressed weights into the model
|
98
|
-
model_device = operator.attrgetter(name)(model).device
|
99
|
-
data_new = Parameter(data.to(model_device))
|
100
|
-
data_old = operator.attrgetter(name)(model)
|
101
|
-
data_old.data = data_new.data
|
102
|
-
|
103
|
-
setattr(model, SPARSITY_CONFIG_NAME, self.config)
|
@@ -14,18 +14,18 @@
|
|
14
14
|
|
15
15
|
from typing import Dict, Generator, Tuple
|
16
16
|
|
17
|
-
from compressed_tensors.compressors import
|
17
|
+
from compressed_tensors.compressors import Compressor
|
18
18
|
from compressed_tensors.config import CompressionFormat
|
19
19
|
from torch import Tensor
|
20
20
|
|
21
21
|
|
22
|
-
@
|
23
|
-
class DenseCompressor(
|
22
|
+
@Compressor.register(name=CompressionFormat.dense.value)
|
23
|
+
class DenseCompressor(Compressor):
|
24
24
|
"""
|
25
25
|
Identity compressor for dense models, returns the original state_dict
|
26
26
|
"""
|
27
27
|
|
28
|
-
def compress(self, model_state: Dict[str, Tensor]) -> Dict[str, Tensor]:
|
28
|
+
def compress(self, model_state: Dict[str, Tensor], **kwargs) -> Dict[str, Tensor]:
|
29
29
|
return model_state
|
30
30
|
|
31
31
|
def decompress(
|
@@ -16,8 +16,8 @@ from pathlib import Path
|
|
16
16
|
from typing import Dict, Generator, Optional, Tuple, Union
|
17
17
|
|
18
18
|
import torch
|
19
|
-
from compressed_tensors.compressors import
|
20
|
-
from compressed_tensors.config import
|
19
|
+
from compressed_tensors.compressors import Compressor
|
20
|
+
from compressed_tensors.config import CompressionFormat, SparsityCompressionConfig
|
21
21
|
from compressed_tensors.utils.safetensors_load import get_weight_mappings
|
22
22
|
from safetensors import safe_open
|
23
23
|
from safetensors.torch import save_file
|
@@ -48,20 +48,20 @@ def save_compressed(
|
|
48
48
|
if tensors is None or len(tensors) == 0:
|
49
49
|
raise ValueError("No tensors or empty tensors provided to compress")
|
50
50
|
|
51
|
-
# if no compression_format specified, default to `
|
52
|
-
compression_format = compression_format or CompressionFormat.
|
51
|
+
# if no compression_format specified, default to `dense`
|
52
|
+
compression_format = compression_format or CompressionFormat.dense.value
|
53
53
|
|
54
54
|
if not (
|
55
|
-
compression_format in
|
56
|
-
or compression_format in
|
55
|
+
compression_format in Compressor.registered_names()
|
56
|
+
or compression_format in Compressor.registered_aliases()
|
57
57
|
):
|
58
58
|
raise ValueError(
|
59
59
|
f"Unknown compression format: {compression_format}. "
|
60
|
-
f"Must be one of {set(
|
60
|
+
f"Must be one of {set(Compressor.registered_names() + Compressor.registered_aliases())}" # noqa E501
|
61
61
|
)
|
62
62
|
|
63
63
|
# compress
|
64
|
-
compressor =
|
64
|
+
compressor = Compressor.load_from_registry(compression_format)
|
65
65
|
# save compressed tensors
|
66
66
|
compressed_tensors = compressor.compress(tensors)
|
67
67
|
save_file(compressed_tensors, save_path)
|
@@ -69,7 +69,7 @@ def save_compressed(
|
|
69
69
|
|
70
70
|
def load_compressed(
|
71
71
|
compressed_tensors: Union[str, Path],
|
72
|
-
compression_config:
|
72
|
+
compression_config: SparsityCompressionConfig = None,
|
73
73
|
device: Optional[str] = "cpu",
|
74
74
|
) -> Generator[Tuple[str, Tensor], None, None]:
|
75
75
|
"""
|
@@ -90,9 +90,9 @@ def load_compressed(
|
|
90
90
|
|
91
91
|
if (
|
92
92
|
compression_config is None
|
93
|
-
or compression_config.format == CompressionFormat.
|
93
|
+
or compression_config.format == CompressionFormat.dense.value
|
94
94
|
):
|
95
|
-
# if no compression_config specified, or `
|
95
|
+
# if no compression_config specified, or `dense` format specified,
|
96
96
|
# assume tensors are not compressed on disk
|
97
97
|
weight_mappings = get_weight_mappings(compressed_tensors)
|
98
98
|
for weight_name, file_with_weight_name in weight_mappings.items():
|
@@ -102,7 +102,7 @@ def load_compressed(
|
|
102
102
|
else:
|
103
103
|
# decompress tensors
|
104
104
|
compression_format = compression_config.format
|
105
|
-
compressor =
|
105
|
+
compressor = Compressor.load_from_registry(
|
106
106
|
compression_format, config=compression_config
|
107
107
|
)
|
108
108
|
yield from compressor.decompress(compressed_tensors, device=device)
|
@@ -0,0 +1,126 @@
|
|
1
|
+
# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing,
|
10
|
+
# software distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
|
15
|
+
import logging
|
16
|
+
from typing import Dict, Generator, Tuple
|
17
|
+
|
18
|
+
import torch
|
19
|
+
from compressed_tensors.compressors import Compressor
|
20
|
+
from compressed_tensors.config import CompressionFormat
|
21
|
+
from compressed_tensors.quantization import QuantizationArgs
|
22
|
+
from compressed_tensors.quantization.lifecycle.forward import dequantize, quantize
|
23
|
+
from compressed_tensors.quantization.utils import can_quantize
|
24
|
+
from compressed_tensors.utils import get_nested_weight_mappings, merge_names
|
25
|
+
from safetensors import safe_open
|
26
|
+
from torch import Tensor
|
27
|
+
from tqdm import tqdm
|
28
|
+
|
29
|
+
|
30
|
+
__all__ = ["IntQuantizationCompressor"]
|
31
|
+
|
32
|
+
_LOGGER: logging.Logger = logging.getLogger(__name__)
|
33
|
+
|
34
|
+
|
35
|
+
@Compressor.register(name=CompressionFormat.int_quantized.value)
|
36
|
+
class IntQuantizationCompressor(Compressor):
|
37
|
+
"""
|
38
|
+
Integer compression for quantized models. Weight of each quantized layer is
|
39
|
+
converted from its original float type to the format specified by the layer's
|
40
|
+
quantization scheme.
|
41
|
+
"""
|
42
|
+
|
43
|
+
COMPRESSION_PARAM_NAMES = ["weight", "weight_scale", "weight_zero_point"]
|
44
|
+
|
45
|
+
def compress(
|
46
|
+
self,
|
47
|
+
model_state: Dict[str, Tensor],
|
48
|
+
model_quant_args: Dict[str, QuantizationArgs],
|
49
|
+
**kwargs,
|
50
|
+
) -> Dict[str, Tensor]:
|
51
|
+
"""
|
52
|
+
Compresses a dense state dict
|
53
|
+
|
54
|
+
:param model_state: state dict of uncompressed model
|
55
|
+
:param model_quant_args: quantization args for each quantized weight, needed for
|
56
|
+
quantize function to calculate bit depth
|
57
|
+
:return: compressed state dict
|
58
|
+
"""
|
59
|
+
compressed_dict = {}
|
60
|
+
weight_suffix = ".weight"
|
61
|
+
_LOGGER.debug(
|
62
|
+
f"Compressing model with {len(model_state)} parameterized layers..."
|
63
|
+
)
|
64
|
+
|
65
|
+
for name, value in tqdm(model_state.items(), desc="Compressing model"):
|
66
|
+
if name.endswith(weight_suffix):
|
67
|
+
prefix = name[: -(len(weight_suffix))]
|
68
|
+
scale = model_state.get(merge_names(prefix, "weight_scale"), None)
|
69
|
+
zp = model_state.get(merge_names(prefix, "weight_zero_point"), None)
|
70
|
+
if scale is not None and zp is not None:
|
71
|
+
# weight is quantized, compress it
|
72
|
+
quant_args = model_quant_args[prefix]
|
73
|
+
if can_quantize(value, quant_args):
|
74
|
+
# only quantize if not already quantized
|
75
|
+
value = quantize(
|
76
|
+
x=value,
|
77
|
+
scale=scale,
|
78
|
+
zero_point=zp,
|
79
|
+
args=quant_args,
|
80
|
+
dtype=torch.int8,
|
81
|
+
)
|
82
|
+
elif name.endswith("zero_point"):
|
83
|
+
if torch.all(value == 0):
|
84
|
+
# all zero_points are 0, no need to include in
|
85
|
+
# compressed state_dict
|
86
|
+
continue
|
87
|
+
compressed_dict[name] = value.to("cpu")
|
88
|
+
|
89
|
+
return compressed_dict
|
90
|
+
|
91
|
+
def decompress(
|
92
|
+
self, path_to_model_or_tensors: str, device: str = "cpu"
|
93
|
+
) -> Generator[Tuple[str, Tensor], None, None]:
|
94
|
+
"""
|
95
|
+
Reads a compressed state dict located at path_to_model_or_tensors
|
96
|
+
and returns a generator for sequentially decompressing back to a
|
97
|
+
dense state dict
|
98
|
+
|
99
|
+
:param model_path: path to compressed safetensors model (directory with
|
100
|
+
one or more safetensors files) or compressed tensors file
|
101
|
+
:param device: optional device to load intermediate weights into
|
102
|
+
:return: compressed state dict
|
103
|
+
"""
|
104
|
+
weight_mappings = get_nested_weight_mappings(
|
105
|
+
path_to_model_or_tensors, self.COMPRESSION_PARAM_NAMES
|
106
|
+
)
|
107
|
+
for weight_name in weight_mappings.keys():
|
108
|
+
weight_data = {}
|
109
|
+
for param_name, safe_path in weight_mappings[weight_name].items():
|
110
|
+
full_name = merge_names(weight_name, param_name)
|
111
|
+
with safe_open(safe_path, framework="pt", device=device) as f:
|
112
|
+
weight_data[param_name] = f.get_tensor(full_name)
|
113
|
+
|
114
|
+
if "weight_scale" in weight_data:
|
115
|
+
zero_point = weight_data.get("weight_zero_point", None)
|
116
|
+
scale = weight_data["weight_scale"]
|
117
|
+
if zero_point is None:
|
118
|
+
# zero_point assumed to be 0 if not included in state_dict
|
119
|
+
zero_point = torch.zeros_like(scale)
|
120
|
+
|
121
|
+
decompressed = dequantize(
|
122
|
+
x_q=weight_data["weight"],
|
123
|
+
scale=scale,
|
124
|
+
zero_point=zero_point,
|
125
|
+
)
|
126
|
+
yield merge_names(weight_name, "weight"), decompressed
|
@@ -0,0 +1,250 @@
|
|
1
|
+
# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing,
|
10
|
+
# software distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
|
15
|
+
import logging
|
16
|
+
from typing import Dict, Generator, Tuple
|
17
|
+
|
18
|
+
import numpy as np
|
19
|
+
import torch
|
20
|
+
from compressed_tensors.compressors import Compressor
|
21
|
+
from compressed_tensors.compressors.utils import (
|
22
|
+
get_permutations_24,
|
23
|
+
sparse_semi_structured_from_dense_cutlass,
|
24
|
+
tensor_follows_mask_structure,
|
25
|
+
)
|
26
|
+
from compressed_tensors.config import CompressionFormat
|
27
|
+
from compressed_tensors.quantization import QuantizationArgs, QuantizationStrategy
|
28
|
+
from compressed_tensors.quantization.lifecycle.forward import quantize
|
29
|
+
from compressed_tensors.utils import is_quantization_param, merge_names
|
30
|
+
from torch import Tensor
|
31
|
+
from tqdm import tqdm
|
32
|
+
|
33
|
+
|
34
|
+
_LOGGER: logging.Logger = logging.getLogger(__name__)
|
35
|
+
|
36
|
+
|
37
|
+
@Compressor.register(name=CompressionFormat.marlin_24.value)
|
38
|
+
class Marlin24Compressor(Compressor):
|
39
|
+
"""
|
40
|
+
Compresses a quantized model with 2:4 sparsity structure for inference with the
|
41
|
+
Marlin24 kernel. Decompression is not implemented for this compressor.
|
42
|
+
"""
|
43
|
+
|
44
|
+
COMPRESSION_PARAM_NAMES = ["weight_packed", "scale_packed", "meta"]
|
45
|
+
|
46
|
+
@staticmethod
|
47
|
+
def validate_quant_compatability(
|
48
|
+
model_quant_args: Dict[str, QuantizationArgs]
|
49
|
+
) -> bool:
|
50
|
+
"""
|
51
|
+
Checks if every quantized module in the model is compatible with Marlin24
|
52
|
+
compression. Quantization must be channel or group strategy with group_size
|
53
|
+
of 128. Only symmetric quantization is supported
|
54
|
+
|
55
|
+
:param model_quant_args: dictionary of mapping module names to their
|
56
|
+
quantization configuration
|
57
|
+
:return: True if all modules are compatible with Marlin24 compression, raises
|
58
|
+
a ValueError otherwise
|
59
|
+
"""
|
60
|
+
for name, quant_args in model_quant_args.items():
|
61
|
+
strategy = quant_args.strategy
|
62
|
+
group_size = quant_args.group_size
|
63
|
+
symmetric = quant_args.symmetric
|
64
|
+
if (
|
65
|
+
strategy is not QuantizationStrategy.GROUP.value
|
66
|
+
and strategy is not QuantizationStrategy.CHANNEL.value
|
67
|
+
):
|
68
|
+
raise ValueError(
|
69
|
+
f"Marlin24 Compressor is only valid for group and channel "
|
70
|
+
f"quantization strategies, got {strategy} in {name}"
|
71
|
+
)
|
72
|
+
|
73
|
+
if group_size is not None and group_size != 128:
|
74
|
+
raise ValueError(
|
75
|
+
f"Marlin24 Compressor is only valid for group size 128, "
|
76
|
+
f"got {group_size} in {name}"
|
77
|
+
)
|
78
|
+
|
79
|
+
if not symmetric:
|
80
|
+
raise ValueError(
|
81
|
+
f"Marlin24 Compressor is only valid for symmetric quantzation, "
|
82
|
+
f"got symmetric={symmetric} in {name}"
|
83
|
+
)
|
84
|
+
|
85
|
+
return True
|
86
|
+
|
87
|
+
@staticmethod
|
88
|
+
def validate_sparsity_structure(name: str, weight: Tensor) -> bool:
|
89
|
+
"""
|
90
|
+
Checks if a tensor fits the required 2:4 sparsity structure
|
91
|
+
|
92
|
+
:param name: name of the tensor to check
|
93
|
+
:param weight: tensor to check for sparsity structure
|
94
|
+
:return: True if all rows match the 2:4 sparsity structure, raises
|
95
|
+
ValueError otherwise
|
96
|
+
"""
|
97
|
+
|
98
|
+
if not tensor_follows_mask_structure(weight):
|
99
|
+
raise ValueError(
|
100
|
+
"Marlin24 Compressor is only compatible with weights that have "
|
101
|
+
f"a 2:4 sparsity structure. Found segments in {name} "
|
102
|
+
"that do not match the expected structure."
|
103
|
+
)
|
104
|
+
|
105
|
+
return True
|
106
|
+
|
107
|
+
def compress(
|
108
|
+
self,
|
109
|
+
model_state: Dict[str, Tensor],
|
110
|
+
model_quant_args: Dict[str, QuantizationArgs],
|
111
|
+
**kwargs,
|
112
|
+
) -> Dict[str, Tensor]:
|
113
|
+
"""
|
114
|
+
Compresses a quantized state_dict with 2:4 sparsity structure for inference
|
115
|
+
with the Marlin24 kernel
|
116
|
+
|
117
|
+
:param model_state: state dict of uncompressed model
|
118
|
+
:param model_quant_args: quantization args for each quantized weight, needed for
|
119
|
+
quantize function to calculate bit depth
|
120
|
+
:return: compressed state dict
|
121
|
+
"""
|
122
|
+
self.validate_quant_compatability(model_quant_args)
|
123
|
+
|
124
|
+
compressed_dict = {}
|
125
|
+
weight_suffix = ".weight"
|
126
|
+
_LOGGER.debug(
|
127
|
+
f"Compressing model with {len(model_state)} parameterized layers..."
|
128
|
+
)
|
129
|
+
|
130
|
+
for name, value in tqdm(model_state.items(), desc="Compressing model"):
|
131
|
+
if name.endswith(weight_suffix):
|
132
|
+
prefix = name[: -(len(weight_suffix))]
|
133
|
+
scale = model_state.get(merge_names(prefix, "weight_scale"), None)
|
134
|
+
zp = model_state.get(merge_names(prefix, "weight_zero_point"), None)
|
135
|
+
if scale is not None: # weight is quantized, compress it
|
136
|
+
|
137
|
+
# Marlin24 kernel requires float16 inputs
|
138
|
+
scale = scale.to(torch.float16)
|
139
|
+
value = value.to(torch.float16)
|
140
|
+
|
141
|
+
# quantize weight, keeping it as a float16 for now
|
142
|
+
quant_args = model_quant_args[prefix]
|
143
|
+
value = quantize(
|
144
|
+
x=value, scale=scale, zero_point=zp, args=quant_args
|
145
|
+
)
|
146
|
+
|
147
|
+
# compress based on sparsity structure
|
148
|
+
self.validate_sparsity_structure(prefix, value)
|
149
|
+
value, meta = compress_weight_24(value)
|
150
|
+
meta = meta.cpu()
|
151
|
+
|
152
|
+
# Marlin24 kernel expects input dim first
|
153
|
+
value = value.t().contiguous().cpu()
|
154
|
+
scale = scale.t().contiguous().cpu()
|
155
|
+
og_weight_shape = value.shape
|
156
|
+
|
157
|
+
# Marlin24 kernel expects unsigned values, shift zero-point
|
158
|
+
value += (1 << quant_args.num_bits) // 2
|
159
|
+
|
160
|
+
# pack quantized weight and scale
|
161
|
+
value = pack_weight_24(value, quant_args)
|
162
|
+
packed_scale = pack_scales_24(scale, quant_args, og_weight_shape)
|
163
|
+
meta = meta.resize_(meta.shape[1] // 2, meta.shape[0] * 2)
|
164
|
+
|
165
|
+
# save compressed values
|
166
|
+
compressed_dict[merge_names(prefix, "scale_packed")] = packed_scale
|
167
|
+
compressed_dict[merge_names(prefix, "weight_packed")] = value
|
168
|
+
compressed_dict[merge_names(prefix, "meta")] = meta
|
169
|
+
continue
|
170
|
+
|
171
|
+
if not is_quantization_param(name):
|
172
|
+
# export unquantized parameters without modifying
|
173
|
+
compressed_dict[name] = value.to("cpu")
|
174
|
+
|
175
|
+
return compressed_dict
|
176
|
+
|
177
|
+
def decompress(
|
178
|
+
self, path_to_model_or_tensors: str, device: str = "cpu"
|
179
|
+
) -> Generator[Tuple[str, Tensor], None, None]:
|
180
|
+
raise NotImplementedError(
|
181
|
+
"Decompression is not implemented for the Marlin24 Compressor."
|
182
|
+
)
|
183
|
+
|
184
|
+
|
185
|
+
def compress_weight_24(weight: Tensor):
|
186
|
+
weight = weight.contiguous()
|
187
|
+
w_comp, meta = sparse_semi_structured_from_dense_cutlass(weight)
|
188
|
+
w_comp = w_comp.contiguous()
|
189
|
+
return w_comp, meta
|
190
|
+
|
191
|
+
|
192
|
+
def marlin_permute_weights(q_w, size_k, size_n, perm, tile):
|
193
|
+
assert q_w.shape == (size_k, size_n)
|
194
|
+
assert size_k % tile == 0, f"size_k = {size_k}, tile = {tile}"
|
195
|
+
assert size_n % tile == 0, f"size_k = {size_n}, tile = {tile}"
|
196
|
+
|
197
|
+
# Permute weights to 16x64 marlin tiles
|
198
|
+
q_w = q_w.reshape((size_k // tile, tile, size_n // tile, tile))
|
199
|
+
q_w = q_w.permute((0, 2, 1, 3))
|
200
|
+
q_w = q_w.reshape((size_k // tile, size_n * tile))
|
201
|
+
|
202
|
+
q_w = q_w.reshape((-1, perm.numel()))[:, perm].reshape(q_w.shape)
|
203
|
+
|
204
|
+
return q_w
|
205
|
+
|
206
|
+
|
207
|
+
def pack_weight_24(
|
208
|
+
weight: Tensor,
|
209
|
+
quantization_args: QuantizationArgs,
|
210
|
+
tile: int = 16,
|
211
|
+
):
|
212
|
+
size_k = weight.shape[0]
|
213
|
+
size_n = weight.shape[1]
|
214
|
+
num_bits = quantization_args.num_bits
|
215
|
+
pack_factor = 32 // num_bits
|
216
|
+
|
217
|
+
# Reshuffle to marlin_24 format
|
218
|
+
perm, _, _ = get_permutations_24(num_bits)
|
219
|
+
q_w = marlin_permute_weights(weight, size_k, size_n, perm, tile)
|
220
|
+
|
221
|
+
q_w = q_w.cpu().numpy().astype(np.uint32)
|
222
|
+
|
223
|
+
q_packed = np.zeros((q_w.shape[0], q_w.shape[1] // pack_factor), dtype=np.uint32)
|
224
|
+
for i in range(pack_factor):
|
225
|
+
q_packed |= q_w[:, i::pack_factor] << num_bits * i
|
226
|
+
|
227
|
+
q_packed = torch.from_numpy(q_packed.astype(np.int32))
|
228
|
+
|
229
|
+
return q_packed
|
230
|
+
|
231
|
+
|
232
|
+
def pack_scales_24(scales, quantization_args, w_shape):
|
233
|
+
size_k = w_shape[0]
|
234
|
+
size_n = w_shape[1]
|
235
|
+
num_bits = quantization_args.num_bits
|
236
|
+
|
237
|
+
_, scale_perm_2_4, scale_perm_single_2_4 = get_permutations_24(num_bits)
|
238
|
+
|
239
|
+
if (
|
240
|
+
quantization_args.strategy is QuantizationStrategy.GROUP
|
241
|
+
and quantization_args.group_size < size_k
|
242
|
+
):
|
243
|
+
scales = scales.reshape((-1, len(scale_perm_2_4)))[:, scale_perm_2_4]
|
244
|
+
else: # channelwise
|
245
|
+
scales = scales.reshape((-1, len(scale_perm_single_2_4)))[
|
246
|
+
:, scale_perm_single_2_4
|
247
|
+
]
|
248
|
+
scales = scales.reshape((-1, size_n)).contiguous()
|
249
|
+
|
250
|
+
return scales
|