File size: 10,103 Bytes
6fe1473
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import torch
import json
import os
import struct
import numpy as np
from transformers import AutoModelForCausalLM, AutoConfig
from collections import OrderedDict
from tqdm import tqdm


def quantize_tensor_symmetric(tensor, bits_per_param):
    """

    Symmetric linear quantization with zero-point preservation.



    Args:

        tensor: Input float tensor

        bits_per_param: Bit width for quantization (2,3,4,5,6,8,12,16,32)



    Returns:

        quantized_signed: Signed integer tensor

        scale: Quantization scale factor

        level: Maximum absolute level L = 2^(bits-1)-1

        dtype_name: String descriptor

    """
    if bits_per_param == 32:
        return tensor.to(torch.float32), None, None, "float32"
    elif bits_per_param == 16:
        return tensor.to(torch.float16), None, None, "float16"

    max_abs = tensor.abs().max().item()
    if max_abs == 0:
        max_abs = 1e-8

    L = 2 ** (bits_per_param - 1) - 1
    scale = max_abs / L
    quantized = (tensor / scale).round().clamp(-L, L)

    dtype_name = f"int{bits_per_param}_sym"
    storage_dtype = torch.int8 if bits_per_param <= 8 else torch.int16
    return quantized.to(storage_dtype), scale, L, dtype_name


def pack_2bit(values):
    """Pack 4 unsigned 2-bit values into 1 byte."""
    shape = values.shape
    flat = values.flatten().to(torch.uint8)
    pad = (4 - len(flat) % 4) % 4
    if pad:
        flat = torch.cat([flat, torch.zeros(pad, dtype=torch.uint8)])
    flat = flat.view(-1, 4)
    packed = ((flat[:, 0] & 0x03) |
              ((flat[:, 1] & 0x03) << 2) |
              ((flat[:, 2] & 0x03) << 4) |
              ((flat[:, 3] & 0x03) << 6))
    return packed, shape, pad


def pack_3bit(values):
    """Pack 8 unsigned 3-bit values into 3 bytes."""
    shape = values.shape
    flat = values.flatten().to(torch.uint8)
    pad = (8 - len(flat) % 8) % 8
    if pad:
        flat = torch.cat([flat, torch.zeros(pad, dtype=torch.uint8)])
    flat = flat.view(-1, 8)
    packed = torch.zeros(len(flat) * 3, dtype=torch.uint8)
    packed[0::3] = ((flat[:, 0] & 0x07) |
                    ((flat[:, 1] & 0x07) << 3) |
                    ((flat[:, 2] & 0x03) << 6))
    packed[1::3] = (((flat[:, 2] >> 2) & 0x01) |
                    ((flat[:, 3] & 0x07) << 1) |
                    ((flat[:, 4] & 0x07) << 4) |
                    ((flat[:, 5] & 0x01) << 7))
    packed[2::3] = (((flat[:, 5] >> 1) & 0x03) |
                    ((flat[:, 6] & 0x07) << 2) |
                    ((flat[:, 7] & 0x07) << 5))
    return packed, shape, pad


def pack_4bit(values):
    """Pack 2 unsigned 4-bit values into 1 byte."""
    shape = values.shape
    flat = values.flatten().to(torch.uint8)
    pad = (2 - len(flat) % 2) % 2
    if pad:
        flat = torch.cat([flat, torch.zeros(pad, dtype=torch.uint8)])
    flat = flat.view(-1, 2)
    packed = ((flat[:, 0] & 0x0F) |
              ((flat[:, 1] & 0x0F) << 4))
    return packed, shape, pad


def pack_5bit(values):
    """Pack 8 unsigned 5-bit values into 5 bytes."""
    shape = values.shape
    flat = values.flatten().to(torch.uint8)
    pad = (8 - len(flat) % 8) % 8
    if pad:
        flat = torch.cat([flat, torch.zeros(pad, dtype=torch.uint8)])
    flat = flat.view(-1, 8)
    packed = torch.zeros(len(flat) * 5, dtype=torch.uint8)
    packed[0::5] = ((flat[:, 0] & 0x1F) |
                    ((flat[:, 1] & 0x07) << 5))
    packed[1::5] = (((flat[:, 1] >> 3) & 0x03) |
                    ((flat[:, 2] & 0x1F) << 2) |
                    ((flat[:, 3] & 0x01) << 7))
    packed[2::5] = (((flat[:, 3] >> 1) & 0x0F) |
                    ((flat[:, 4] & 0x0F) << 4))
    packed[3::5] = (((flat[:, 4] >> 4) & 0x01) |
                    ((flat[:, 5] & 0x1F) << 1) |
                    ((flat[:, 6] & 0x03) << 6))
    packed[4::5] = (((flat[:, 6] >> 2) & 0x07) |
                    ((flat[:, 7] & 0x1F) << 3))
    return packed, shape, pad


def pack_6bit(values):
    """Pack 4 unsigned 6-bit values into 3 bytes."""
    shape = values.shape
    flat = values.flatten().to(torch.uint8)
    pad = (4 - len(flat) % 4) % 4
    if pad:
        flat = torch.cat([flat, torch.zeros(pad, dtype=torch.uint8)])
    flat = flat.view(-1, 4)
    packed = torch.zeros(len(flat) * 3, dtype=torch.uint8)
    packed[0::3] = ((flat[:, 0] & 0x3F) |
                    ((flat[:, 1] & 0x03) << 6))
    packed[1::3] = (((flat[:, 1] >> 2) & 0x0F) |
                    ((flat[:, 2] & 0x0F) << 4))
    packed[2::3] = (((flat[:, 2] >> 4) & 0x03) |
                    ((flat[:, 3] & 0x3F) << 2))
    return packed, shape, pad


def pack_12bit(values):
    """Pack 2 unsigned 12-bit values into 3 bytes."""
    shape = values.shape
    flat = values.flatten().to(torch.uint16)
    pad = (2 - len(flat) % 2) % 2
    if pad:
        flat = torch.cat([flat, torch.zeros(pad, dtype=torch.uint16)])
    flat = flat.view(-1, 2)
    a = flat[:, 0].numpy().astype(np.uint16)
    b = flat[:, 1].numpy().astype(np.uint16)
    byte0 = a & 0xFF
    byte1 = ((a >> 8) & 0x0F) | ((b & 0x0F) << 4)
    byte2 = (b >> 4) & 0xFF
    packed = np.stack([byte0, byte1, byte2], axis=1).flatten().astype(np.uint8)
    return torch.from_numpy(packed), shape, pad


def convert_to_dq(model_path, output_path, bits_per_param=8):
    """

    Convert HuggingFace model to .dq quantized format.



    Args:

        model_path: Path to local HuggingFace model directory

        output_path: Output path for .dq file

        bits_per_param: Target bit width (2, 3, 4, 5, 6, 8, 12, 16, 32)



    Format specification:

        Magic: 'DQMD' (4 bytes)

        Version: uint32 (4 bytes)

        Global metadata: length (uint32) + JSON bytes

        Tensor headers: length (uint32) + JSON bytes

        Tensor data: raw bytes per tensor in header order

    """
    config = AutoConfig.from_pretrained(model_path)
    model = AutoModelForCausalLM.from_pretrained(
        model_path,
        torch_dtype=torch.float32,
        low_cpu_mem_usage=True
    )

    state_dict = model.state_dict()

    dq_data = {
        'config': config.to_dict(),
        'bits_per_param': bits_per_param,
        'tensors': OrderedDict(),
        'metadata': {
            'model_path': model_path,
            'architecture': config.architectures[0] if hasattr(config, 'architectures') else 'unknown'
        }
    }

    pack_functions = {
        2: pack_2bit,
        3: pack_3bit,
        4: pack_4bit,
        5: pack_5bit,
        6: pack_6bit,
        12: pack_12bit,
    }

    total_params = 0

    with tqdm(total=len(state_dict), desc="Quantizing") as pbar:
        for name, tensor in state_dict.items():
            total_params += tensor.numel()

            quantized_signed, scale, level, dtype_name = quantize_tensor_symmetric(
                tensor, bits_per_param
            )

            tensor_info = {
                'shape': list(tensor.shape),
                'dtype': dtype_name,
                'scale': scale,
                'level': level,
            }

            if bits_per_param in pack_functions:
                unsigned = quantized_signed.to(torch.int32) + level
                if bits_per_param <= 8:
                    unsigned = unsigned.to(torch.uint8)
                else:
                    unsigned = unsigned.to(torch.uint16)

                packed, original_shape, pad_len = pack_functions[bits_per_param](unsigned)
                tensor_info['data'] = packed.numpy().tobytes()
                tensor_info['packed'] = True
                tensor_info['packed_shape'] = list(original_shape)
                tensor_info['pad'] = pad_len
                del unsigned, packed
            elif bits_per_param == 8:
                unsigned = (quantized_signed.to(torch.int32) + level).to(torch.uint8)
                tensor_info['data'] = unsigned.numpy().tobytes()
                tensor_info['packed'] = False
                del unsigned
            elif bits_per_param in (16, 32):
                tensor_info['data'] = quantized_signed.numpy().tobytes()
                tensor_info['packed'] = False

            dq_data['tensors'][name] = tensor_info
            del tensor, quantized_signed
            pbar.update(1)

    serializable_tensors = OrderedDict()
    for name, info in dq_data['tensors'].items():
        serializable_tensors[name] = {k: v for k, v in info.items() if k != 'data'}
        serializable_tensors[name]['data_size'] = len(info['data'])

    with open(output_path, 'wb') as f:
        f.write(b'DQMD')
        f.write(struct.pack('<I', 1))

        global_meta = {
            'config': dq_data['config'],
            'bits_per_param': dq_data['bits_per_param'],
            'metadata': dq_data['metadata']
        }
        global_meta_json = json.dumps(global_meta).encode('utf-8')
        f.write(struct.pack('<I', len(global_meta_json)))
        f.write(global_meta_json)

        tensor_headers_json = json.dumps(serializable_tensors).encode('utf-8')
        f.write(struct.pack('<I', len(tensor_headers_json)))
        f.write(tensor_headers_json)

        for info in dq_data['tensors'].values():
            f.write(info['data'])

    original_size_mb = total_params * 4 / 1024 ** 2
    compressed_size_mb = os.path.getsize(output_path) / 1024 ** 2
    ratio = (total_params * 4) / os.path.getsize(output_path)

    return {
        'total_params': total_params,
        'bits_per_param': bits_per_param,
        'original_size_mb': original_size_mb,
        'compressed_size_mb': compressed_size_mb,
        'compression_ratio': ratio,
        'output_path': output_path
    }


if __name__ == "__main__":
    result = convert_to_dq("modelHF", "modelDQ.dq", bits_per_param=8)
    print(f"Conversion complete: {result['compression_ratio']:.2f}x compression "
          f"({result['original_size_mb']:.1f}MB -> {result['compressed_size_mb']:.1f}MB)")