fbaldassarri commited on
Commit
e108ba6
·
verified ·
1 Parent(s): 2d59050

Initial Upload

Browse files
LICENSE.md ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ LLAMA 3.2 COMMUNITY LICENSE AGREEMENT
2
+
3
+ Llama 3.2 Version Release Date: September 25, 2024
4
+
5
+ “Agreement” means the terms and conditions for use, reproduction, distribution and modification of the Llama Materials set forth herein.
6
+
7
+
8
+ “Documentation” means the specifications, manuals and documentation accompanying Llama 3.2 distributed by Meta at https://www.llama.com/docs/overview.
9
+
10
+
11
+ “Licensee” or “you” means you, or your employer or any other person or entity (if you are entering into this Agreement on such person or entity’s behalf), of the age required under applicable laws, rules or regulations to provide legal consent and that has legal authority to bind your employer or such other person or entity if you are entering in this Agreement on their behalf.
12
+
13
+
14
+ “Llama 3.2” means the foundational large language models and software and algorithms, including machine-learning model code, trained model weights, inference-enabling code, training-enabling code, fine-tuning enabling code and other elements of the foregoing distributed by Meta at https://www.llama.com/llama-downloads.
15
+
16
+
17
+ “Llama Materials” means, collectively, Meta’s proprietary Llama 3.2 and Documentation (and any portion thereof) made available under this Agreement.
18
+
19
+
20
+ “Meta” or “we” means Meta Platforms Ireland Limited (if you are located in or, if you are an entity, your principal place of business is in the EEA or Switzerland) and Meta Platforms, Inc. (if you are located outside of the EEA or Switzerland).
21
+
22
+
23
+ By clicking “I Accept” below or by using or distributing any portion or element of the Llama Materials, you agree to be bound by this Agreement.
24
+
25
+
26
+ 1. License Rights and Redistribution.
27
+
28
+
29
+ a. Grant of Rights. You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Meta’s intellectual property or other rights owned by Meta embodied in the Llama Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the Llama Materials.
30
+
31
+
32
+ b. Redistribution and Use.
33
+
34
+
35
+ i. If you distribute or make available the Llama Materials (or any derivative works thereof), or a product or service (including another AI model) that contains any of them, you shall (A) provide a copy of this Agreement with any such Llama Materials; and (B) prominently display “Built with Llama” on a related website, user interface, blogpost, about page, or product documentation. If you use the Llama Materials or any outputs or results of the Llama Materials to create, train, fine tune, or otherwise improve an AI model, which is distributed or made available, you shall also include “Llama” at the beginning of any such AI model name.
36
+
37
+
38
+ ii. If you receive Llama Materials, or any derivative works thereof, from a Licensee as part of an integrated end user product, then Section 2 of this Agreement will not apply to you.
39
+
40
+
41
+ iii. You must retain in all copies of the Llama Materials that you distribute the following attribution notice within a “Notice” text file distributed as a part of such copies: “Llama 3.2 is licensed under the Llama 3.2 Community License, Copyright © Meta Platforms, Inc. All Rights Reserved.”
42
+
43
+
44
+ iv. Your use of the Llama Materials must comply with applicable laws and regulations (including trade compliance laws and regulations) and adhere to the Acceptable Use Policy for the Llama Materials (available at https://www.llama.com/llama3_2/use-policy), which is hereby incorporated by reference into this Agreement.
45
+
46
+ 2. Additional Commercial Terms. If, on the Llama 3.2 version release date, the monthly active users of the products or services made available by or for Licensee, or Licensee’s affiliates, is greater than 700 million monthly active users in the preceding calendar month, you must request a license from Meta, which Meta may grant to you in its sole discretion, and you are not authorized to exercise any of the rights under this Agreement unless or until Meta otherwise expressly grants you such rights.
47
+
48
+
49
+ 3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE LLAMA MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OF ANY KIND, AND META DISCLAIMS ALL WARRANTIES OF ANY KIND, BOTH EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE LLAMA MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE LLAMA MATERIALS AND ANY OUTPUT AND RESULTS.
50
+
51
+
52
+ 4. Limitation of Liability. IN NO EVENT WILL META OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
53
+
54
+
55
+ 5. Intellectual Property.
56
+
57
+
58
+ a. No trademark licenses are granted under this Agreement, and in connection with the Llama Materials, neither Meta nor Licensee may use any name or mark owned by or associated with the other or any of its affiliates, except as required for reasonable and customary use in describing and redistributing the Llama Materials or as set forth in this Section 5(a). Meta hereby grants you a license to use “Llama” (the “Mark”) solely as required to comply with the last sentence of Section 1.b.i. You will comply with Meta’s brand guidelines (currently accessible at https://about.meta.com/brand/resources/meta/company-brand/). All goodwill arising out of your use of the Mark will inure to the benefit of Meta.
59
+
60
+
61
+ b. Subject to Meta’s ownership of Llama Materials and derivatives made by or for Meta, with respect to any derivative works and modifications of the Llama Materials that are made by you, as between you and Meta, you are and will be the owner of such derivative works and modifications.
62
+
63
+
64
+ c. If you institute litigation or other proceedings against Meta or any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Llama Materials or Llama 3.2 outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Meta from and against any claim by any third party arising out of or related to your use or distribution of the Llama Materials.
65
+
66
+
67
+ 6. Term and Termination. The term of this Agreement will commence upon your acceptance of this Agreement or access to the Llama Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Meta may terminate this Agreement if you are in breach of any term or condition of this Agreement. Upon termination of this Agreement, you shall delete and cease use of the Llama Materials. Sections 3, 4 and 7 shall survive the termination of this Agreement.
68
+
69
+
70
+ 7. Governing Law and Jurisdiction. This Agreement will be governed and construed under the laws of the State of California without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The courts of California shall have exclusive jurisdiction of any dispute arising out of this Agreement.
README.md ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ - de
5
+ - fr
6
+ - it
7
+ - pt
8
+ - hi
9
+ - es
10
+ - th
11
+ license: llama3.2
12
+ library_name: transformers
13
+ tags:
14
+ - woq
15
+ - intel-neural-compressor
16
+ - inc
17
+ - neural-compressor
18
+ - intel
19
+ - teq
20
+ - meta
21
+ - pytorch
22
+ - llama
23
+ - llama-3
24
+ model_name: Llama 3.2 3B
25
+ base_model: meta-llama/Llama-3.2-3B
26
+ inference: false
27
+ model_creator: meta-llama
28
+ pipeline_tag: text-generation
29
+ prompt_template: '{prompt}
30
+ '
31
+ quantized_by: fbaldassarri
32
+ ---
33
+
34
+ ## Model Information
35
+
36
+ Quantized version of [meta-llama/Llama-3.2-3B](https://huggingface.co/meta-llama/Llama-3.2-3B) using torch.float32 for quantization tuning.
37
+ - 4 bits (INT4)
38
+ - group size = 128
39
+ - Asymmetrical Quantization
40
+ - Algorith method: TEQ (Trainable Equivalent Transformation for Quantization of LLMs)
41
+
42
+ Quantization framework: [Intel Neural Compressor](https://github.com/intel/neural-compressor/) version 3.3.1
43
+
44
+ Note: this INT4 version of Llama-3.2-3B has been quantized to run inference through CPU.
45
+
46
+ ## Disclaimer
47
+
48
+ This quantized model comes with no warrenty. It has been developed experimetally only for research purposes.
49
+
50
+ This repository only contains contains two files: quantized_model.pt (weights structure) and qconfig.json, and the generated model is a quantized model.
51
+ It needs to be used in combination with the base model meta-llama/Llama-3.2-3B.
52
+
53
+ ## Replication Recipe
54
+
55
+ ```
56
+ $ conda create --name neural-compressor-3.3.1 --file requirements_conda_neural-compressor-3.3.1
57
+
58
+ $ python meta-llama_Llama-3.2-3B-TEQ-int4-gs128-asym.py
59
+ ```
60
+
61
+ ## Run Inference
62
+
63
+ To run inference you can use [fbaldassarri/woq-inference](https://github.com/fbaldassarri/woq-inference).
64
+
65
+ ```
66
+ python teq_inference.py --base meta-llama/Llama-3.2-3B --model_dir ./meta-llama_Llama-3.2-3B-TEQ-int4-gs128-asym --weights_file quantized_weight.pt --config_file qconfig.json --prompt "What If you have got superpowers?" --device cpu
67
+ ```
68
+
69
+ Note: You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
70
+
71
+ ## License
72
+
73
+ [Llama 3.2 Community License](https://github.com/meta-llama/llama-models/blob/main/models/llama3_2/LICENSE)
meta-llama_Llama-3.2-3B-TEQ-int4-gs128-asym.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import time
4
+ import random
5
+ import torch
6
+
7
+ from collections import UserDict
8
+ from packaging.version import Version
9
+ from datasets import load_dataset
10
+ from torch.utils.data import DataLoader
11
+ from transformers import AutoModelForCausalLM, AutoTokenizer
12
+
13
+ from neural_compressor.common import logger
14
+ from neural_compressor.torch.utils import is_hpex_available, get_torch_version
15
+
16
+ # ====== utils.py content inlined and fixed ======
17
+
18
+ class DataloaderPreprocessor:
19
+ def __init__(self, dataloader_original, use_max_length=False, max_seq_length=2048, nsamples=128) -> None:
20
+ self.dataloader_original = dataloader_original
21
+ self.use_max_length = use_max_length
22
+ self.max_seq_length = max_seq_length
23
+ self.nsamples = nsamples
24
+ self.dataloader = []
25
+ self.is_ready = False
26
+
27
+ def get_prepared_dataloader(self):
28
+ if not self.is_ready:
29
+ self.prepare_dataloader()
30
+ return self.dataloader
31
+
32
+ def prepare_dataloader(self):
33
+ if self.use_max_length:
34
+ self.obtain_first_n_samples_fulllength()
35
+ else:
36
+ self.obtain_first_n_samples()
37
+ self.is_ready = True
38
+
39
+ def obtain_first_n_samples(self, seed=0):
40
+ """Get first nsample data as the real calibration dataset."""
41
+ self.dataloader.clear()
42
+ random.seed(seed)
43
+ for batch in self.dataloader_original:
44
+ if len(self.dataloader) == self.nsamples:
45
+ logger.info(f"Successfully collect {self.nsamples} calibration samples.")
46
+ break
47
+ # list, tuple
48
+ if isinstance(batch, list) or isinstance(batch, tuple):
49
+ if batch[0].shape[-1] > self.max_seq_length:
50
+ i = random.randint(0, batch[0].shape[-1] - self.max_seq_length - 1)
51
+ j = i + self.max_seq_length
52
+ batch_final = []
53
+ for item in batch:
54
+ if isinstance(item, torch.Tensor) and item.ndim == 2:
55
+ batch_final.append(item[:, i:j])
56
+ else:
57
+ batch_final.append(item)
58
+ else:
59
+ batch_final = batch[:]
60
+ # dict
61
+ elif isinstance(batch, dict):
62
+ try:
63
+ length = batch["input_ids"].shape[-1]
64
+ except Exception:
65
+ logger.warning("Please make sure your dict'like data contains key of 'input_ids'.")
66
+ continue
67
+ batch_final = {}
68
+ if length > self.max_seq_length:
69
+ i = random.randint(0, length - self.max_seq_length - 1)
70
+ j = i + self.max_seq_length
71
+ for key in batch.keys():
72
+ if isinstance(batch[key], torch.Tensor):
73
+ batch_final[key] = batch[key][:, i:j]
74
+ else:
75
+ batch_final[key] = batch[key]
76
+ else:
77
+ batch_final = batch
78
+ # tensor
79
+ else:
80
+ if batch.shape[-1] > self.max_seq_length:
81
+ i = random.randint(0, batch.shape[-1] - self.max_seq_length - 1)
82
+ j = i + self.max_seq_length
83
+ batch_final = batch[:, i:j]
84
+ else:
85
+ batch_final = batch
86
+ self.dataloader.append(batch_final)
87
+ if len(self.dataloader) < self.nsamples:
88
+ logger.warning(f"Try to use {self.nsamples} data, but entire dataset size is {len(self.dataloader)}.")
89
+
90
+ def obtain_first_n_samples_fulllength(self, seed=0):
91
+ self.dataloader.clear()
92
+ random.seed(seed)
93
+ unified_length = self.max_seq_length
94
+ for batch in self.dataloader_original:
95
+ if len(self.dataloader) == self.nsamples:
96
+ logger.info(f"Successfully collect {self.nsamples} calibration samples.")
97
+ break
98
+ # list & tuple
99
+ if isinstance(batch, list) or isinstance(batch, tuple):
100
+ if batch[0].shape[-1] == unified_length:
101
+ batch_final = batch[:]
102
+ elif batch[0].shape[-1] > unified_length:
103
+ i = random.randint(0, batch[0].shape[-1] - unified_length - 1)
104
+ j = i + unified_length
105
+ batch_final = []
106
+ for item in batch:
107
+ if isinstance(item, torch.Tensor) and item.ndim == 2:
108
+ batch_final.append(item[:, i:j])
109
+ else:
110
+ batch_final.append(item)
111
+ else:
112
+ continue
113
+ # dict
114
+ elif isinstance(batch, dict):
115
+ try:
116
+ length = batch["input_ids"].shape[-1]
117
+ except Exception:
118
+ logger.warning("Please make sure your dict'like data contains key of 'input_ids'.")
119
+ continue
120
+ batch_final = {}
121
+ if length == self.max_seq_length:
122
+ batch_final = batch
123
+ elif length > self.max_seq_length:
124
+ i = random.randint(0, length - self.max_seq_length - 1)
125
+ j = i + self.max_seq_length
126
+ for key in batch.keys():
127
+ if isinstance(batch[key], torch.Tensor):
128
+ batch_final[key] = batch[key][:, i:j]
129
+ else:
130
+ batch_final[key] = batch[key]
131
+ else:
132
+ continue
133
+ # tensor
134
+ else:
135
+ if batch.shape[-1] == unified_length:
136
+ batch_final = batch
137
+ elif batch.shape[-1] > unified_length:
138
+ i = random.randint(0, batch.shape[-1] - unified_length - 1)
139
+ j = i + unified_length
140
+ batch_final = batch[:, i:j]
141
+ else:
142
+ continue
143
+ self.dataloader.append(batch_final)
144
+ if len(self.dataloader) < self.nsamples:
145
+ logger.warning(
146
+ f"Trying to allocate {self.nsamples} data with fixed length {unified_length}, "
147
+ f"but only {len(self.dataloader)} samples are found. Please use smaller 'self.max_seq_length' value."
148
+ )
149
+
150
+ def get_example_inputs(model, dataloader):
151
+ version = get_torch_version()
152
+ from neural_compressor.torch.algorithms.smooth_quant import move_input_to_device
153
+ if dataloader is None:
154
+ return None
155
+ device = next(model.parameters()).device
156
+ try:
157
+ for idx, (input, label) in enumerate(dataloader):
158
+ input = move_input_to_device(input, device)
159
+ if isinstance(input, (dict, UserDict)):
160
+ assert version.release >= Version("1.12.0").release, "INC support IPEX version >= 1.12.0"
161
+ if "label" in input.keys():
162
+ input.pop("label")
163
+ if version.release <= Version("2.0.1").release:
164
+ return tuple(input.values())
165
+ else:
166
+ return dict(input)
167
+ if isinstance(input, (list, tuple)):
168
+ return tuple(input)
169
+ if isinstance(input, torch.Tensor):
170
+ return input
171
+ break
172
+ except Exception as e:
173
+ for idx, input in enumerate(dataloader):
174
+ input = move_input_to_device(input, device)
175
+ if isinstance(input, (dict, UserDict)):
176
+ assert version.release >= Version("1.12.0").release, "INC support IPEX version >= 1.12.0"
177
+ if "label" in input.keys():
178
+ input.pop("label")
179
+ if version.release <= Version("2.0.1").release:
180
+ return tuple(input.values())
181
+ else:
182
+ return dict(input)
183
+ if isinstance(input, list) or isinstance(input, tuple):
184
+ return tuple(input)
185
+ if isinstance(input, torch.Tensor):
186
+ return input
187
+ break
188
+ if idx == 0:
189
+ assert False, "Please checkout the example_inputs format."
190
+
191
+ # ====== End of utils.py content ======
192
+
193
+ # ====== Hardcoded arguments ======
194
+ class Args:
195
+ model = "meta-llama/Llama-3.2-3B"
196
+ trust_remote_code = True
197
+ revision = None
198
+ dataset = "neuralmagic/LLM_compression_calibration"
199
+ output_dir = "meta-llama_Llama-3.2-3B-TEQ-int4-gs128-asym"
200
+ quantize = True
201
+ seed = 42
202
+ load = False
203
+ accuracy = False
204
+ performance = False
205
+ iters = 100
206
+ batch_size = 1
207
+ pad_max_length = 512
208
+ calib_iters = 512
209
+ tasks = "lambada_openai,hellaswag,winogrande,piqa"
210
+ peft_model_id = None
211
+
212
+ # Weight-only quantization configs
213
+ woq_algo = "TEQ"
214
+ woq_bits = 4
215
+ woq_dtype = "int"
216
+ woq_group_size = 128
217
+ woq_group_dim = 1
218
+ woq_scheme = "asym"
219
+ woq_use_mse_search = False
220
+ woq_use_full_range = False
221
+ quant_lm_head = True
222
+ use_hf_format = False
223
+
224
+ # TEQ/AWQ configs
225
+ use_auto_scale = False
226
+ use_auto_clip = False
227
+ folding = False
228
+ absorb_layer_dict = {}
229
+
230
+ # DoubleQuant configs
231
+ double_quant_type = None
232
+ double_quant_dtype = "fp32"
233
+ double_quant_bits = 8
234
+ double_quant_use_sym = True
235
+ double_quant_group_size = 256
236
+
237
+ args = Args()
238
+ calib_size = 1
239
+
240
+ if is_hpex_available():
241
+ import habana_frameworks.torch.core as htcore
242
+ htcore.hpu_set_inference_env()
243
+ device = "hpu"
244
+ else:
245
+ device = "cpu"
246
+
247
+ # ====== Helper functions ======
248
+ def get_user_model():
249
+ torchscript = False
250
+ if args.woq_algo in ["AWQ", "TEQ"]:
251
+ torchscript = True
252
+ user_model = AutoModelForCausalLM.from_pretrained(
253
+ args.model,
254
+ torchscript=torchscript,
255
+ trust_remote_code=args.trust_remote_code,
256
+ revision=args.revision,
257
+ )
258
+ tokenizer = AutoTokenizer.from_pretrained(args.model)
259
+ user_model = user_model.float()
260
+ user_model = user_model.to(memory_format=torch.channels_last)
261
+ user_model.eval()
262
+ return user_model, tokenizer
263
+
264
+ def calib_func(prepared_model):
265
+ for i, calib_input in enumerate(calib_dataloader):
266
+ if i > args.calib_iters:
267
+ break
268
+ prepared_model(calib_input[0])
269
+
270
+ # ====== Main quantization logic ======
271
+ if args.quantize:
272
+ user_model, tokenizer = get_user_model()
273
+ calib_dataset = load_dataset(args.dataset, split="train")
274
+ calib_dataset = calib_dataset.shuffle(seed=args.seed)
275
+
276
+ class Evaluator:
277
+ def __init__(self, dataset, tokenizer, batch_size=8, pad_val=1, pad_max=196, is_calib=False):
278
+ self.dataset = dataset
279
+ self.tokenizer = tokenizer
280
+ self.batch_size = batch_size
281
+ self.pad_val = pad_val
282
+ self.pad_max = pad_max
283
+ self.is_calib = is_calib
284
+ self.dataset = self.dataset.map(self.tokenize_function, batched=True)
285
+ self.dataset.set_format(type="torch", columns=["input_ids"])
286
+
287
+ @torch.no_grad()
288
+ def tokenize_function(self, examples):
289
+ if args.woq_algo in ['TEQ']:
290
+ if self.tokenizer.pad_token is None:
291
+ self.tokenizer.pad_token = self.tokenizer.eos_token
292
+ example = self.tokenizer(examples["text"], padding="max_length", max_length=self.pad_max)
293
+ else:
294
+ example = self.tokenizer(examples["text"])
295
+ return example
296
+
297
+ @torch.no_grad()
298
+ def collate_batch(self, batch):
299
+ input_ids_padded = []
300
+ last_ind = []
301
+ for text in batch:
302
+ input_ids = text["input_ids"]
303
+ pad_len = self.pad_max - input_ids.shape[0]
304
+ last_ind.append(input_ids.shape[0] - 1)
305
+ input_ids = input_ids[:self.pad_max] if len(input_ids) > self.pad_max else input_ids
306
+ input_ids = torch.nn.functional.pad(input_ids, (0, pad_len), value=self.pad_val)
307
+ input_ids_padded.append(input_ids)
308
+ return (torch.vstack(input_ids_padded), torch.tensor(last_ind))
309
+
310
+ calib_evaluator = Evaluator(calib_dataset, tokenizer, args.batch_size, pad_max=args.pad_max_length, is_calib=True)
311
+ calib_dataloader = DataLoader(
312
+ calib_evaluator.dataset,
313
+ batch_size=calib_size,
314
+ shuffle=False,
315
+ collate_fn=calib_evaluator.collate_batch,
316
+ )
317
+
318
+ # === TEQ quantization ===
319
+ from neural_compressor.torch.quantization import TEQConfig, prepare, convert
320
+
321
+ weight_sym = True if args.woq_scheme == "sym" else False
322
+ quant_config = TEQConfig(
323
+ dtype=args.woq_dtype,
324
+ bits=args.woq_bits,
325
+ use_sym=weight_sym,
326
+ group_size=args.woq_group_size,
327
+ group_dim=args.woq_group_dim,
328
+ folding=args.folding,
329
+ quant_lm_head=args.quant_lm_head,
330
+ )
331
+
332
+ example_inputs = torch.ones([1, args.pad_max_length], dtype=torch.long)
333
+ run_fn = calib_func
334
+
335
+ user_model = prepare(model=user_model, quant_config=quant_config, example_inputs=example_inputs)
336
+ run_fn(user_model)
337
+ user_model = convert(user_model)
338
+
339
+ # === Save quantized model ===
340
+ os.makedirs(args.output_dir, exist_ok=True)
341
+ print("Saving weight-only quantized model to", args.output_dir)
342
+ if args.use_hf_format:
343
+ user_model.save(args.output_dir, format="huggingface")
344
+ tokenizer.save_pretrained(args.output_dir)
345
+ else:
346
+ user_model.save(args.output_dir)
347
+ print("Saved weight-only quantized model.")
348
+
349
+ else:
350
+ print("Quantization not enabled. Exiting.")
qconfig.json ADDED
The diff for this file is too large to render. See raw diff
 
quantized_weight.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a03ad8af0ab9cf94cdb5e6baa4627b31a6d9ed86a664baf61731209bc0824a8
3
+ size 3250917925
requirements_conda_neural-compressor-3.3.1.txt ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file may be used to create an environment using:
2
+ # $ conda create --name <env> --file <this file>
3
+ # platform: linux-64
4
+ # created-by: conda 24.11.3
5
+ _libgcc_mutex=0.1=main
6
+ _openmp_mutex=5.1=1_gnu
7
+ absl-py=2.2.2=pypi_0
8
+ accelerate=1.6.0=pypi_0
9
+ aiohappyeyeballs=2.6.1=pypi_0
10
+ aiohttp=3.11.18=pypi_0
11
+ aiosignal=1.3.2=pypi_0
12
+ annotated-types=0.7.0=pypi_0
13
+ astunparse=1.6.3=pypi_0
14
+ attrs=25.3.0=pypi_0
15
+ auto-round=0.5.1=pypi_0
16
+ bzip2=1.0.8=h5eee18b_6
17
+ ca-certificates=2025.2.25=h06a4308_0
18
+ certifi=2025.1.31=pypi_0
19
+ chardet=5.2.0=pypi_0
20
+ charset-normalizer=3.4.1=pypi_0
21
+ click=8.1.8=pypi_0
22
+ colorama=0.4.6=pypi_0
23
+ contourpy=1.3.2=pypi_0
24
+ cycler=0.12.1=pypi_0
25
+ dataproperty=1.1.0=pypi_0
26
+ datasets=3.5.0=pypi_0
27
+ deprecated=1.2.18=pypi_0
28
+ dill=0.3.8=pypi_0
29
+ docker-pycreds=0.4.0=pypi_0
30
+ einops=0.8.1=pypi_0
31
+ evaluate=0.4.3=pypi_0
32
+ filelock=3.13.1=pypi_0
33
+ flatbuffers=25.2.10=pypi_0
34
+ fonttools=4.57.0=pypi_0
35
+ frozenlist=1.6.0=pypi_0
36
+ fsspec=2024.6.1=pypi_0
37
+ gast=0.6.0=pypi_0
38
+ gitdb=4.0.12=pypi_0
39
+ gitpython=3.1.44=pypi_0
40
+ google-pasta=0.2.0=pypi_0
41
+ grpcio=1.71.0=pypi_0
42
+ h5py=3.13.0=pypi_0
43
+ huggingface-hub=0.30.2=pypi_0
44
+ idna=3.10=pypi_0
45
+ iniconfig=2.1.0=pypi_0
46
+ jinja2=3.1.4=pypi_0
47
+ joblib=1.4.2=pypi_0
48
+ jsonlines=4.0.0=pypi_0
49
+ keras=3.9.2=pypi_0
50
+ kiwisolver=1.4.8=pypi_0
51
+ ld_impl_linux-64=2.40=h12ee557_0
52
+ libclang=18.1.1=pypi_0
53
+ libffi=3.4.4=h6a678d5_1
54
+ libgcc-ng=11.2.0=h1234567_1
55
+ libgomp=11.2.0=h1234567_1
56
+ libstdcxx-ng=11.2.0=h1234567_1
57
+ libuuid=1.41.5=h5eee18b_0
58
+ llvmlite=0.44.0=pypi_0
59
+ lm-eval=0.4.3=pypi_0
60
+ lxml=5.4.0=pypi_0
61
+ markdown=3.8=pypi_0
62
+ markdown-it-py=3.0.0=pypi_0
63
+ markupsafe=2.1.5=pypi_0
64
+ matplotlib=3.10.1=pypi_0
65
+ mbstrdecoder=1.1.4=pypi_0
66
+ mdurl=0.1.2=pypi_0
67
+ ml-dtypes=0.5.1=pypi_0
68
+ more-itertools=10.7.0=pypi_0
69
+ mpmath=1.3.0=pypi_0
70
+ multidict=6.4.3=pypi_0
71
+ multiprocess=0.70.16=pypi_0
72
+ namex=0.0.9=pypi_0
73
+ ncurses=6.4=h6a678d5_0
74
+ networkx=3.3=pypi_0
75
+ neural-compressor=3.3.1=pypi_0
76
+ nltk=3.9.1=pypi_0
77
+ numba=0.61.2=pypi_0
78
+ numexpr=2.10.2=pypi_0
79
+ numpy=1.26.4=pypi_0
80
+ opencv-python-headless=4.11.0.86=pypi_0
81
+ openssl=3.0.16=h5eee18b_0
82
+ opt-einsum=3.4.0=pypi_0
83
+ optree=0.15.0=pypi_0
84
+ packaging=25.0=pypi_0
85
+ pandas=2.2.3=pypi_0
86
+ pathvalidate=3.2.3=pypi_0
87
+ peft=0.15.2=pypi_0
88
+ pillow=11.0.0=pypi_0
89
+ pip=25.0=py311h06a4308_0
90
+ platformdirs=4.3.7=pypi_0
91
+ pluggy=1.5.0=pypi_0
92
+ portalocker=3.1.1=pypi_0
93
+ prettytable=3.16.0=pypi_0
94
+ propcache=0.3.1=pypi_0
95
+ protobuf=5.29.4=pypi_0
96
+ psutil=7.0.0=pypi_0
97
+ py-cpuinfo=9.0.0=pypi_0
98
+ pyarrow=19.0.1=pypi_0
99
+ pybind11=2.13.6=pypi_0
100
+ pycocotools=2.0.8=pypi_0
101
+ pydantic=2.11.3=pypi_0
102
+ pydantic-core=2.33.1=pypi_0
103
+ pygments=2.19.1=pypi_0
104
+ pyparsing=3.2.3=pypi_0
105
+ pytablewriter=1.2.1=pypi_0
106
+ pytest=8.3.5=pypi_0
107
+ python=3.11.11=he870216_0
108
+ python-dateutil=2.9.0.post0=pypi_0
109
+ pytz=2025.2=pypi_0
110
+ pyyaml=6.0.2=pypi_0
111
+ readline=8.2=h5eee18b_0
112
+ regex=2024.11.6=pypi_0
113
+ requests=2.32.3=pypi_0
114
+ rich=14.0.0=pypi_0
115
+ rouge-score=0.1.2=pypi_0
116
+ sacrebleu=2.5.1=pypi_0
117
+ safetensors=0.5.3=pypi_0
118
+ schema=0.7.7=pypi_0
119
+ scikit-learn=1.6.1=pypi_0
120
+ scipy=1.15.2=pypi_0
121
+ sentencepiece=0.2.0=pypi_0
122
+ sentry-sdk=2.27.0=pypi_0
123
+ setproctitle=1.3.5=pypi_0
124
+ setuptools=75.8.0=py311h06a4308_0
125
+ six=1.17.0=pypi_0
126
+ smmap=5.0.2=pypi_0
127
+ sqlite=3.45.3=h5eee18b_0
128
+ sqlitedict=2.1.0=pypi_0
129
+ sympy=1.13.3=pypi_0
130
+ tabledata=1.3.4=pypi_0
131
+ tabulate=0.9.0=pypi_0
132
+ tbb=2022.1.0=pypi_0
133
+ tcmlib=1.3.0=pypi_0
134
+ tcolorpy=0.1.7=pypi_0
135
+ tensorboard=2.19.0=pypi_0
136
+ tensorboard-data-server=0.7.2=pypi_0
137
+ tensorflow-cpu=2.19.0=pypi_0
138
+ tensorflow-io-gcs-filesystem=0.37.1=pypi_0
139
+ termcolor=3.0.1=pypi_0
140
+ threadpoolctl=3.6.0=pypi_0
141
+ tk=8.6.14=h39e8969_0
142
+ tokenizers=0.21.1=pypi_0
143
+ torch=2.7.0+cpu=pypi_0
144
+ torchaudio=2.7.0+cpu=pypi_0
145
+ torchvision=0.22.0+cpu=pypi_0
146
+ tqdm=4.67.1=pypi_0
147
+ tqdm-multiprocess=0.0.11=pypi_0
148
+ transformers=4.51.3=pypi_0
149
+ typepy=1.3.4=pypi_0
150
+ typing-extensions=4.12.2=pypi_0
151
+ typing-inspection=0.4.0=pypi_0
152
+ tzdata=2025.2=pypi_0
153
+ urllib3=2.4.0=pypi_0
154
+ wandb=0.19.10=pypi_0
155
+ wcwidth=0.2.13=pypi_0
156
+ werkzeug=3.1.3=pypi_0
157
+ wheel=0.45.1=py311h06a4308_0
158
+ word2number=1.1=pypi_0
159
+ wrapt=1.17.2=pypi_0
160
+ xxhash=3.5.0=pypi_0
161
+ xz=5.6.4=h5eee18b_1
162
+ yarl=1.20.0=pypi_0
163
+ zlib=1.2.13=h5eee18b_1
164
+ zstandard=0.23.0=pypi_0