JustJaro commited on
Commit
63fdc58
·
verified ·
1 Parent(s): dd95b0e

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +1 -470
README.md CHANGED
@@ -10,474 +10,5 @@ tags:
10
  ---
11
  # 🔥 Quantized Model: Arcee-Blitz_gptq_g32_4bit 🔥
12
 
13
- This is a 4-bit quantized version of [arcee-ai/Arcee-Blitz](https://huggingface.co/arcee-ai/Arcee-Blitz) model, quantized by [ConfidentialMind.com](https://www.confidentialmind.com) 🤖✨
14
- It leverages the open-source GPTQModel quantization to achieve 4-bit precision with a group size of 128 resulting in a
15
- smaller,
16
- faster model with minimal performance degradation.
17
 
18
- Ran on a single NVIDIA A100 GPU with 80GB of VRAM.
19
-
20
- *Note* `batch_size` is set quite high as the model is small, you may need to adjust this to your GPU VRAM.
21
-
22
- ## Model Details
23
- - **Original Model:** [arcee-ai/Arcee-Blitz](https://huggingface.co/arcee-ai/Arcee-Blitz)
24
- - **Quantized Model:** Arcee-Blitz_gptq_g32_4bit (this repository)
25
- - **Quantization Method:** GPTQ (4-bit, group size 128)
26
- - **Quantization Library:** [GPTQModel](https://github.com/ModelCloud/GPTQModel/tree/main)
27
- - **Calibration Dataset:** neuralmagic/LLM_compression_calibration (using 1024 samples with seq len 4096)
28
- - **Quantized by:** [ConfidentialMind.com](https://www.confidentialmind.com)
29
-
30
- ## Usage
31
-
32
- ```python
33
- from gptqmodel import GPTQModel
34
- from transformers import AutoTokenizer
35
-
36
- # Use the local directory or JustJaro/Arcee-Blitz_gptq_g32_4bit after upload
37
- quantized_model_id = "/home/jaro/models/quantized/Arcee-Blitz_gptq_g32_4bit" # or "JustJaro/Arcee-Blitz_gptq_g32_4bit"
38
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_id)
39
- model = GPTQModel.load(quantized_model_id, device="cuda:0") # or "cpu"
40
-
41
- input_text = "This is a test prompt"
42
- inputs = tokenizer(input_text, return_tensors="pt").to("cuda:0")
43
- outputs = model.generate(**inputs)
44
- print(tokenizer.decode(outputs[0], skip_special_tokens=True))
45
- ```
46
-
47
- ## Package Versions and Installation Instructions
48
-
49
- See pyproject.toml for the exact UV project file. See the [GPTQModel](
50
- https://github.com/ModelCloud/GPTQModel/tree/main) repo for more details. on how to install the package.
51
-
52
- Use the provided pyproject.toml:
53
-
54
- ```bash
55
- uv venv
56
- source venv/bin/activate
57
- uv sync
58
- ```
59
-
60
- ### Environment Variables
61
-
62
- ```bash
63
- HF_TOKEN=<YOUR_HF_TOKEN>
64
- TOKENIZERS_PARALLELISM="true"
65
- PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
66
- ```
67
-
68
- ## Quantization Script
69
- Below is the exact quantize.py script used to generate this model (with the exact versions of the dependencies):
70
-
71
- ```python
72
- #!/usr/bin/env python3
73
- """
74
- This script loads a source Hugging Face model and a calibration dataset,
75
- quantizes the model using GPTQModel (with 4-bit precision and group size 128),
76
- saves the quantized model using the Transformers API with safetensors (safe serialization)
77
- under ~/models/quantized/, and then creates/updates a Hugging Face repository (with the
78
- _gptq_g128_4bit suffix) by uploading the model, tokenizer, and an auto-generated README.md.
79
-
80
- Usage example:
81
- python quantize.py --source-model TinyLlama/TinyLlama-1.1B-Chat-v1.0 \
82
- --calibration-dataset wikitext/wikitext-2-raw-v1 \
83
- --seq-len 1024 --nsamples 256 --hf-token <YOUR_HF_TOKEN>
84
- """
85
-
86
- import os
87
- import shutil
88
- import subprocess
89
- from enum import Enum
90
- from pathlib import Path
91
- from typing import List
92
-
93
- import torch
94
- import typer
95
- from datasets import load_dataset
96
- from dotenv import load_dotenv, find_dotenv
97
- from gptqmodel import GPTQModel, QuantizeConfig
98
- from gptqmodel.utils import Perplexity
99
- # For later pushing to the model hub
100
- from huggingface_hub import HfApi
101
- from transformers import AutoTokenizer, PreTrainedTokenizerBase
102
-
103
- load_dotenv(find_dotenv())
104
- HF_TOKEN = os.getenv("HF_TOKEN")
105
-
106
- app = typer.Typer()
107
-
108
- class GroupSize(str, Enum):
109
- accurate:int = 32
110
- balanced:int = 64
111
- fast:int = 128
112
-
113
-
114
- def get_text_from_example(example: dict) -> str:
115
- """
116
- Returns text from a dataset example.
117
- If the example contains a "text" field, and it is nonempty, that text is used.
118
- Otherwise, if it has a "messages" field (a list of dicts with a "content" key),
119
- the function returns the concatenation of all non-empty message contents.
120
- """
121
- if "text" in example and example["text"]:
122
- return example["text"]
123
- elif "messages" in example:
124
- contents = [msg.get("content", "").strip() for msg in example["messages"]]
125
- return " ".join([s for s in contents if s])
126
- else:
127
- return ""
128
-
129
-
130
- def get_calibration_dataset(
131
- tokenizer: PreTrainedTokenizerBase,
132
- nsamples: int,
133
- seqlen: int,
134
- calibration_dataset: str
135
- ) -> List[dict]:
136
- """
137
- Loads a calibration dataset from the Hugging Face Hub (or from a local file).
138
- It accepts datasets with a single "text" field (like wikitext)
139
- or with a "messages" field (as in the Neural Magic LLM Compression Calibration dataset).
140
- Only examples whose extracted text length is at least 'seqlen' are kept.
141
- Each chosen example is tokenized (with truncation up to 'seqlen') and returned as a dict.
142
- """
143
- ds = None
144
- try:
145
- # Attempt to load from HF Hub.
146
- try:
147
- if "/" in calibration_dataset:
148
- parts = calibration_dataset.split("/", 1)
149
- ds = load_dataset(parts[0], parts[1], split="train")
150
- else:
151
- ds = load_dataset(calibration_dataset, split="train")
152
- except Exception as e:
153
- print(f"Error loading dataset '{calibration_dataset}' via load_dataset: {e}")
154
- ds = load_dataset(calibration_dataset, split="train")
155
- print(f"Loaded calibration dataset from full remote path {calibration_dataset}.")
156
-
157
-
158
- except Exception as e:
159
- print(f"Error loading dataset '{calibration_dataset}' via load_dataset: {e}")
160
- # Fallback: if the supplied calibration_dataset is a local path, try to load it as JSON-lines.
161
- if os.path.exists(calibration_dataset):
162
- try:
163
- ds = load_dataset("json", data_files=calibration_dataset, split="train")
164
- print(f"Loaded calibration dataset from local file {calibration_dataset}.")
165
- except Exception as e2:
166
- print(f"Error loading local json dataset from '{calibration_dataset}': {e2}")
167
- return []
168
- else:
169
- return []
170
-
171
- print(f"Dataset features: {ds.features}")
172
-
173
- # Filter examples that have at least 80% 'seqlen' of extracted text (wikitext-2-raw-v1 dataset has short examples).
174
- ds = ds.filter(lambda x: len(get_text_from_example(x)) <= int(seqlen*0.8))
175
- sample_range = min(nsamples, len(ds))
176
- calibration_data = []
177
- for i in range(sample_range):
178
- example = ds[i]
179
- text = get_text_from_example(example)
180
- tokenized = tokenizer(text, truncation=True, max_length=seqlen, return_tensors="pt")
181
- tokenized = {k: v.squeeze(0) for k, v in tokenized.items()}
182
- calibration_data.append(tokenized)
183
- return calibration_data
184
-
185
-
186
- def calculate_avg_ppl(model, tokenizer):
187
- """
188
- Computes the average perplexity on the wikitext-2-raw-v1 train split using GPTQModel's Perplexity utility.
189
- """
190
- ppl = Perplexity(
191
- model=model,
192
- tokenizer=tokenizer,
193
- dataset_path="wikitext",
194
- dataset_name="wikitext-2-raw-v1",
195
- split="train",
196
- text_column="text",
197
- )
198
- ppl_values = ppl.calculate(n_ctx=512, n_batch=512)
199
- avg = sum(ppl_values) / len(ppl_values)
200
- return avg
201
-
202
-
203
- def get_pinned_package_versions():
204
- """
205
- Retrieves pinned package versions using 'uv pip freeze'.
206
- Returns a dictionary mapping lowercased package names to their versions.
207
- """
208
- try:
209
- result = subprocess.run(["uv", "pip", "freeze"], capture_output=True, text=True, check=True)
210
- packages_output = result.stdout.strip()
211
- versions = {}
212
- for line in packages_output.splitlines():
213
- if "==" in line:
214
- package_name, package_version = line.split("==", 1)
215
- versions[package_name.lower()] = package_version
216
- return versions
217
- except subprocess.CalledProcessError as e:
218
- typer.echo(f"Error running 'uv pip freeze': {e}", err=True)
219
- return {}
220
- except FileNotFoundError:
221
- typer.echo("uv command not found. Make sure uv is installed and in your PATH.", err=True)
222
- return {}
223
-
224
-
225
- @app.command()
226
- def main(
227
- seq_len: int = typer.Option(4096, help="Sequence length for tokenization and calibration."),
228
- nsamples: int = typer.Option(512, help="Number of samples to use for calibration."),
229
- source_model: str = typer.Option("rombodawg/Rombos-LLM-V2.6-Qwen-14b",
230
- help="Source model HF repository identifier."),
231
- calibration_dataset: str = typer.Option("wikitext/wikitext-2-raw-v1",
232
- help="Calibration dataset identifier (in 'dataset/config' format) or local file path."),
233
- hf_token: str = typer.Option(HF_TOKEN,
234
- help="Hugging Face token for creating/updating your repo."),
235
- upload_only: bool = typer.Option(False, help="Only upload the quantized model to the Hugging Face Hub."),
236
- # Allow for 32, 64, 128 only using typer:
237
- group_size: GroupSize = typer.Option(GroupSize.accurate, help="Group size for quantization accurate: 32, "
238
- "balanced: 64, fast: 128. Default: accurate."),
239
- mse: bool = typer.Option(True, help="Use mse instead of mae for the loss function."),
240
- size_multi: int = typer.Option(3.5, help="Model size multiplier depends on the source model. Default: 1."),
241
- ):
242
- # Prepare destination directory and model names.
243
- model_name = source_model.split("/")[-1]
244
- if not size_multi == 1:
245
- size_multiplier = size_multi
246
- size_multiplier_len = size_multiplier / 2
247
- else:
248
- size_multiplier = 1
249
- size_multiplier_len = 1
250
- nsamples = int(nsamples * size_multiplier)
251
- seq_len = int(seq_len * size_multiplier_len)
252
- quantized_model_name = f"{model_name}_gptq_g{int(group_size.value)}_4bit"
253
- quantized_model_dir = os.path.expanduser(os.path.join("~/models/quantized", quantized_model_name))
254
- if not upload_only:
255
- # Remove the directory if it already exists
256
- if os.path.exists(quantized_model_dir):
257
- shutil.rmtree(quantized_model_dir)
258
- # Create directory for quantized model.
259
- os.makedirs(quantized_model_dir, exist_ok=True)
260
-
261
- typer.echo("Loading tokenizer from source model...")
262
- tokenizer_obj = AutoTokenizer.from_pretrained(source_model, use_fast=True)
263
-
264
- typer.echo("Loading calibration dataset...")
265
- typer.echo(f"Calibration dataset: {calibration_dataset}")
266
- calibration_data = get_calibration_dataset(tokenizer_obj, nsamples, seq_len, calibration_dataset)
267
- if not calibration_data:
268
- typer.echo("Calibration dataset is empty. Aborting.", err=True)
269
- raise typer.Exit(code=1)
270
- if mse:
271
- # Fits mistral-small-24b particularly well, as well as the increased damp_percent
272
- mse = 0.01
273
- quantize_config = QuantizeConfig(bits=4, group_size=int(group_size.value), damp_percent=0.015, mse=mse)
274
- else:
275
- quantize_config = QuantizeConfig(bits=4, group_size=int(group_size.value), damp_percent=0.01)
276
- device = "cuda:0" if torch.cuda.is_available() else "cpu"
277
- typer.echo(f"Loading model in {device} mode...")
278
- model = GPTQModel.load(source_model, quantize_config)
279
-
280
- typer.echo("Quantizing model...")
281
- group_size_factor = int(128 / int(group_size.value))
282
- model.quantize(calibration_data, auto_gc=False,
283
- batch_size=max(1, int(int((nsamples * 0.1) / group_size_factor) *
284
- int(size_multiplier_len))))
285
- # Retrieve Hugging Face user info for README generation.
286
- package_versions = get_pinned_package_versions()
287
- username = get_my_user(hf_token)
288
-
289
- script_content = self_read_script()
290
-
291
- typer.echo(f"Saving quantized model to {quantized_model_dir} using Transformers safe serialization...")
292
- try:
293
- model.save_pretrained(quantized_model_dir)
294
- tokenizer_obj.save_pretrained(quantized_model_dir)
295
- except Exception as ex:
296
- typer.echo(f"Error during saving with safe_serialization: {ex}. Aborting.")
297
- raise
298
- typer.echo(f"Model uploaded to Hugging Face repo: {quantized_model_name}")
299
- else:
300
- tokenizer_obj = AutoTokenizer.from_pretrained(source_model, use_fast=True)
301
- package_versions = get_pinned_package_versions()
302
- username = get_my_user(hf_token)
303
- script_content = self_read_script()
304
-
305
-
306
- device = "cuda:0" if torch.cuda.is_available() else "cpu"
307
- model = GPTQModel.load(quantized_model_dir, device=device)
308
- avg_ppl = calculate_avg_ppl(model, tokenizer_obj)
309
- typer.echo(f"Average perplexity (PPL) on wikitext v2 dataset: {avg_ppl}")
310
- deps = Path("./pyproject.toml")
311
- shutil.copy(deps, quantized_model_dir)
312
- generate_readme(calibration_dataset, nsamples, quantized_model_dir,
313
- quantized_model_name, script_content, seq_len, source_model, username, avg_ppl)
314
- GPTQModel.push_to_hub(quantized_path=quantized_model_dir, private=False, repo_id=quantized_model_name,
315
- token=HF_TOKEN)
316
- typer.echo(f"Model uploaded to Hugging Face repo: {quantized_model_name}")
317
- demo_input = tokenizer_obj("test is", return_tensors="pt").to(device)
318
- generated_ids = model.generate(**demo_input)
319
- output_text = tokenizer_obj.decode(generated_ids[0])
320
- typer.echo(f"Inference demo output: {output_text}")
321
- typer.echo(f"Average perplexity (PPL) on calibration dataset: {avg_ppl}")
322
-
323
-
324
- def self_read_script():
325
- try:
326
- script_path = os.path.abspath(__file__)
327
- with open(script_path, "r") as f:
328
- script_content = f.read()
329
- except Exception as e:
330
- script_content = "Error reading script content: " + str(e)
331
- return script_content
332
-
333
-
334
- def get_my_user(hf_token):
335
- api = HfApi(token=hf_token)
336
- user_info = api.whoami()
337
- try:
338
- username = user_info.get("name") or user_info.get("username")
339
- except Exception as e:
340
- typer.echo(f"Error retrieving username from Hugging Face API: {e}. Using default username.")
341
- username = api.whoami()
342
- if not username:
343
- typer.echo("Could not determine your Hugging Face username from the token, defaulting to hard coded username.",
344
- err=True)
345
- username = "JustJaro"
346
- return username
347
-
348
-
349
- def generate_readme(calibration_dataset, nsamples, quantized_model_dir,
350
- quantized_model_name, script_content, seq_len, source_model, username, avg_ppl):
351
- readme_content = f"""---
352
- tags:
353
- - gptq
354
- - quantization
355
- - 4bit
356
- - confidentialmind
357
- - text-generation
358
- - apache2.0
359
- - mistral-small-24b
360
- ---
361
- # 🔥 Quantized Model: {quantized_model_name} 🔥
362
-
363
- This is a 4-bit quantized version of [{source_model}](https://huggingface.co/{source_model}) model, quantized by [ConfidentialMind.com](https://www.confidentialmind.com) 🤖✨
364
- It leverages the open-source GPTQModel quantization to achieve 4-bit precision with a group size of 128 resulting in a
365
- smaller,
366
- faster model with minimal performance degradation.
367
-
368
- Ran on a single NVIDIA A100 GPU with 80GB of VRAM.
369
-
370
- *Note* `batch_size` is set quite high as the model is small, you may need to adjust this to your GPU VRAM.
371
-
372
- ## Model Details
373
- - **Original Model:** [{source_model}](https://huggingface.co/{source_model})
374
- - **Quantized Model:** {quantized_model_name} (this repository)
375
- - **Quantization Method:** GPTQ (4-bit, group size 128)
376
- - **Quantization Library:** [GPTQModel](https://github.com/ModelCloud/GPTQModel/tree/main)
377
- - **Calibration Dataset:** {calibration_dataset} (using {nsamples} samples with seq len {seq_len})
378
- - **Quantized by:** [ConfidentialMind.com](https://www.confidentialmind.com)
379
-
380
- ## Usage
381
-
382
- ```python
383
- from gptqmodel import GPTQModel
384
- from transformers import AutoTokenizer
385
-
386
- # Use the local directory or {username}/{quantized_model_name} after upload
387
- quantized_model_id = "{quantized_model_dir}" # or "{username}/{quantized_model_name}"
388
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_id)
389
- model = GPTQModel.load(quantized_model_id, device="cuda:0") # or "cpu"
390
-
391
- input_text = "This is a test prompt"
392
- inputs = tokenizer(input_text, return_tensors="pt").to("cuda:0")
393
- outputs = model.generate(**inputs)
394
- print(tokenizer.decode(outputs[0], skip_special_tokens=True))
395
- ```
396
-
397
- ## Package Versions and Installation Instructions
398
-
399
- See pyproject.toml for the exact UV project file. See the [GPTQModel](
400
- https://github.com/ModelCloud/GPTQModel/tree/main) repo for more details. on how to install the package.
401
-
402
- Use the provided pyproject.toml:
403
-
404
- ```bash
405
- uv venv
406
- source venv/bin/activate
407
- uv sync
408
- ```
409
-
410
- ### Environment Variables
411
-
412
- ```bash
413
- HF_TOKEN=<YOUR_HF_TOKEN>
414
- TOKENIZERS_PARALLELISM="true"
415
- PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
416
- ```
417
-
418
- ## Quantization Script
419
- Below is the exact quantize.py script used to generate this model (with the exact versions of the dependencies):
420
-
421
- ```python
422
- {script_content}
423
- ```
424
-
425
- ## Quantization Performance
426
-
427
- Average perplexity (PPL) on wikitext v2 dataset: {avg_ppl}
428
-
429
- ## Disclaimer
430
- This model is for research purposes only. It may inherit limitations and biases from the original model and the quantization process. Please use responsibly and refer to the original model card for more details.
431
-
432
- ## Contact
433
- For any questions or support, please visit [ConfidentialMind.com](https://www.confidentialmind.com) or contact us directly.
434
-
435
- ## License
436
- This model inherits the license from the original model. Please refer to the original model card for more details.
437
- Original model card: `{source_model}`
438
-
439
- ## Author
440
- This model was quantized by [Jaro](https://www.linkedin.com/in/jaroai/)
441
-
442
- ## Acknowledgements
443
- Quantization performed using the GPTQModel pipeline.
444
-
445
- TODO: Add `gptqmodel.utils.eval` integration and auto-generation of eval table.
446
-
447
- ---
448
- *Generated and quantized using GPTQModel.*
449
- """
450
- readme_path = os.path.join(quantized_model_dir, "README.md")
451
- with open(readme_path, "w") as f:
452
- f.write(readme_content)
453
- typer.echo("README.md created with detailed information.")
454
-
455
-
456
- if __name__ == "__main__":
457
- app()
458
- ```
459
-
460
- ## Quantization Performance
461
-
462
- Average perplexity (PPL) on wikitext v2 dataset: 28.71075403372412
463
-
464
- ## Disclaimer
465
- This model is for research purposes only. It may inherit limitations and biases from the original model and the quantization process. Please use responsibly and refer to the original model card for more details.
466
-
467
- ## Contact
468
- For any questions or support, please visit [ConfidentialMind.com](https://www.confidentialmind.com) or contact us directly.
469
-
470
- ## License
471
- This model inherits the license from the original model. Please refer to the original model card for more details.
472
- Original model card: `arcee-ai/Arcee-Blitz`
473
-
474
- ## Author
475
- This model was quantized by [Jaro](https://www.linkedin.com/in/jaroai/)
476
-
477
- ## Acknowledgements
478
- Quantization performed using the GPTQModel pipeline.
479
-
480
- TODO: Add `gptqmodel.utils.eval` integration and auto-generation of eval table.
481
-
482
- ---
483
- *Generated and quantized using GPTQModel.*
 
10
  ---
11
  # 🔥 Quantized Model: Arcee-Blitz_gptq_g32_4bit 🔥
12
 
 
 
 
 
13
 
14
+ The MSE based test did not work out too well; use non-MSE quant.