JustJaro commited on
Commit
6a98195
·
verified ·
1 Parent(s): 0c281cd

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +3 -373
README.md CHANGED
@@ -7,377 +7,7 @@ pinned: true
7
  authors: "JustJaro"
8
  ---
9
 
10
- # ConfidentialMind 🚀🧠
11
 
12
- Generative AI Software Infrastructure Simplified 🎉
13
-
14
- [![Website](https://img.shields.io/badge/Website-confidentialmind.com-blue)](https://confidentialmind.com)
15
- [![Email](https://img.shields.io/badge/Email-info%40confidentialmind.com-orange)](mailto:[email protected])
16
-
17
- # 🔥 Quantized Model: Arcee-Blitz_gptq_g32_4bit 🦾 🔥
18
-
19
-
20
- <details>
21
- <summary><strong>Model Details</strong></summary>
22
-
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 32)
26
- - **Quantization Library:** [GPTQModel](https://github.com/ModelCloud/GPTQModel/tree/main)
27
- - **Calibration Dataset:** neuralmagic/LLM_compression_calibration (using 1536 samples with seq len 6144)
28
- - **Quantized by:** [ConfidentialMind.com](https://www.confidentialmind.com)
29
-
30
- </details>
31
-
32
- <details>
33
- <summary><strong>Usage</strong></summary>
34
-
35
- ```python
36
- from gptqmodel import GPTQModel
37
- from transformers import AutoTokenizer
38
-
39
- # Use the local directory or JustJaro/Arcee-Blitz_gptq_g32_4bit after upload
40
- quantized_model_id = "/home/jaro/models/quantized/Arcee-Blitz_gptq_g32_4bit" # or "JustJaro/Arcee-Blitz_gptq_g32_4bit"
41
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_id)
42
- model = GPTQModel.load(quantized_model_id, device="cuda:0") # or "cpu"
43
-
44
- input_text = "This is a test prompt"
45
- inputs = tokenizer(input_text, return_tensors="pt").to("cuda:0")
46
- outputs = model.generate(**inputs)
47
- print(tokenizer.decode(outputs[0], skip_special_tokens=True))
48
- ```
49
-
50
- </details>
51
-
52
- <details>
53
- <summary><strong>Package Versions and Installation Instructions</strong></summary>
54
-
55
- See `pyproject.toml` for the exact UV project file. See the [GPTQModel](https://github.com/ModelCloud/GPTQModel/tree/main) repo for more details on how to install the package.
56
-
57
- Use the provided `pyproject.toml`:
58
-
59
- ```bash
60
- uv venv
61
- source venv/bin/activate
62
- uv sync
63
- ```
64
-
65
- </details>
66
-
67
- <details>
68
- <summary><strong>Quantization Script</strong></summary>
69
-
70
- Below is the exact `quantize.py` script used to generate this model:
71
-
72
- ```python
73
- #!/usr/bin/env python3
74
- """
75
- This script loads a source Hugging Face model and a calibration dataset,
76
- quantizes the model using GPTQModel (with 4-bit precision and a dynamic group size),
77
- saves the quantized model with Transformers’ safe serialization under ~/models/quantized/,
78
- and then creates/updates a Hugging Face repository by uploading the model, tokenizer,
79
- and an auto–generated README.md that includes proper foldable sections, badges, and warnings.
80
-
81
- Usage example:
82
- python quantize.py --source-model TinyLlama/TinyLlama-1.1B-Chat-v1.0 \
83
- --calibration-dataset wikitext/wikitext-2-raw-v1 \
84
- --seq-len 1024 --nsamples 256 --hf-token <YOUR_HF_TOKEN>
85
- """
86
-
87
- import os
88
- import random
89
- import shutil
90
- import subprocess
91
- from enum import Enum
92
- from pathlib import Path
93
- from typing import List
94
-
95
- import torch
96
- import typer
97
- from datasets import load_dataset
98
- from dotenv import load_dotenv, find_dotenv
99
- from gptqmodel import GPTQModel, QuantizeConfig
100
- from gptqmodel.utils import Perplexity
101
- # For later pushing to the model hub
102
- from huggingface_hub import HfApi
103
- from transformers import AutoTokenizer, PreTrainedTokenizerBase
104
-
105
- load_dotenv(find_dotenv())
106
- HF_TOKEN = os.getenv("HF_TOKEN")
107
-
108
- app = typer.Typer()
109
-
110
-
111
- class GroupSize(str, Enum):
112
- accurate: int = 32
113
- balanced: int = 64
114
- fast: int = 128
115
-
116
-
117
- def get_text_from_example(example: dict) -> str:
118
- """
119
- Returns text from a dataset example.
120
- If the example contains a "text" field, that text is used.
121
- Otherwise, if it has a "messages" field (a list of dicts with a "content" key),
122
- the contents of all messages are concatenated.
123
- """
124
- if "text" in example and example["text"]:
125
- return example["text"]
126
- elif "messages" in example:
127
- contents = [msg.get("content", "").strip() for msg in example["messages"]]
128
- return " ".join([s for s in contents if s])
129
- else:
130
- return ""
131
-
132
-
133
- def get_calibration_dataset(
134
- tokenizer: PreTrainedTokenizerBase,
135
- nsamples: int,
136
- seqlen: int,
137
- calibration_dataset: str
138
- ) -> List[dict]:
139
- """
140
- Loads and tokenizes a calibration dataset from the HF Hub (or a local file).
141
- Only examples with at least 80% of seqlen characters (after extraction) are kept.
142
- """
143
- ds = None
144
- try:
145
- try:
146
- if "/" in calibration_dataset:
147
- parts = calibration_dataset.split("/", 1)
148
- ds = load_dataset(parts[0], parts[1], split="train")
149
- else:
150
- ds = load_dataset(calibration_dataset, split="train")
151
- except Exception as e:
152
- print(f"Error loading dataset '{calibration_dataset}' via load_dataset: {e}")
153
- ds = load_dataset(calibration_dataset, split="train")
154
- print(f"Loaded calibration dataset from full remote path {calibration_dataset}.")
155
- except Exception as e:
156
- print(f"Error loading dataset '{calibration_dataset}' via load_dataset: {e}")
157
- if os.path.exists(calibration_dataset):
158
- try:
159
- ds = load_dataset("json", data_files=calibration_dataset, split="train")
160
- print(f"Loaded calibration dataset from local file {calibration_dataset}.")
161
- except Exception as e2:
162
- print(f"Error loading local json dataset from '{calibration_dataset}': {e2}")
163
- return []
164
- else:
165
- return []
166
-
167
- print(f"Dataset features: {ds.features}")
168
-
169
- ds = ds.filter(lambda x: len(get_text_from_example(x)) <= int(seqlen * 0.8))
170
- sample_range = min(nsamples, len(ds))
171
- calibration_data = []
172
- for i in range(sample_range):
173
- example = ds[i]
174
- text = get_text_from_example(example)
175
- tokenized = tokenizer(text, truncation=True, max_length=seqlen, return_tensors="pt")
176
- tokenized = {k: v.squeeze(0) for k, v in tokenized.items()}
177
- calibration_data.append(tokenized)
178
- return calibration_data
179
-
180
-
181
- def calculate_avg_ppl(model, tokenizer):
182
- """
183
- Computes the average perplexity on the wikitext-2-raw-v1 training split.
184
- """
185
- ppl = Perplexity(
186
- model=model,
187
- tokenizer=tokenizer,
188
- dataset_path="wikitext",
189
- dataset_name="wikitext-2-raw-v1",
190
- split="train",
191
- text_column="text",
192
- )
193
- ppl_values = ppl.calculate(n_ctx=512, n_batch=512)
194
- avg = sum(ppl_values) / len(ppl_values)
195
- return avg
196
-
197
-
198
- def get_pinned_package_versions():
199
- """
200
- Retrieves pinned package versions via 'uv pip freeze'.
201
- """
202
- try:
203
- result = subprocess.run(["uv", "pip", "freeze"], capture_output=True, text=True, check=True)
204
- packages_output = result.stdout.strip()
205
- versions = {}
206
- for line in packages_output.splitlines():
207
- if "==" in line:
208
- package_name, package_version = line.split("==", 1)
209
- versions[package_name.lower()] = package_version
210
- return versions
211
- except subprocess.CalledProcessError as e:
212
- typer.echo(f"Error running 'uv pip freeze': {e}", err=True)
213
- return {}
214
- except FileNotFoundError:
215
- typer.echo("uv command not found. Make sure uv is installed and in your PATH.", err=True)
216
- return {}
217
-
218
-
219
- def prepare_model_dir(model_dir: str):
220
- """Removes the given directory if it exists and creates a new one."""
221
- if os.path.exists(model_dir):
222
- shutil.rmtree(model_dir)
223
- os.makedirs(model_dir, exist_ok=True)
224
-
225
-
226
- def self_read_script():
227
- """Returns the full text of this script."""
228
- try:
229
- script_path = os.path.abspath(__file__)
230
- with open(script_path, "r") as f:
231
- script_content = f.read()
232
- except Exception as e:
233
- script_content = "Error reading script content: " + str(e)
234
- return script_content
235
-
236
-
237
- def get_my_user(hf_token):
238
- """Retrieves your Hugging Face username from your token."""
239
- api = HfApi(token=hf_token)
240
- user_info = api.whoami()
241
- try:
242
- username = user_info.get("name") or user_info.get("username")
243
- except Exception as e:
244
- typer.echo(f"Error retrieving username from Hugging Face API: {e}. Using default username.")
245
- username = api.whoami()
246
- if not username:
247
- typer.echo("Could not determine your Hugging Face username from the token. Using default username.", err=True)
248
- username = "JustJaro"
249
- return username
250
-
251
-
252
- def generate_readme(calibration_dataset, nsamples, quantized_model_dir, quantized_model_name,
253
- script_content, seq_len, source_model, username, avg_ppl, group_size_int):
254
- """
255
- Creates a README.md with dynamic sections:
256
- • A front matter section with badges/links.
257
- • A title that includes a randomly chosen emoji.
258
- • A warning if the perplexity is too high (>30).
259
- • Collapsible sections (using <details>) for model details, usage, installation, script,
260
- quantization performance, disclaimer, contact, license, author and acknowledgements.
261
- • Additional TODO items.
262
- """
263
- # pick a random emoji from the list (for each model, so it varies)
264
- chosen_emoji = random.choice(["⚡️", "🐣", "🦾", "🤖", "🧠", "🧐", "🚀"])
265
-
266
- # Warning if average perplexity is above 30
267
- if avg_ppl > 30:
268
- warning_text = f"\n**⚠️ WARNING: High Perplexity Detected!** The average perplexity is {avg_ppl:.2f}, which exceeds the recommended threshold.\n"
269
- else:
270
- warning_text = ""
271
-
272
- # Front matter with badges and links
273
- front_matter = (
274
- "---\n"
275
- 'company: "ConfidentialMind"\n'
276
- 'emoji: "🧠"\n'
277
- 'colorFrom: "blue"\n'
278
- 'colorTo: "purple"\n'
279
- "pinned: true\n"
280
- 'authors: "JustJaro"\n'
281
- "---\n\n"
282
- "# ConfidentialMind 🚀🧠\n\n"
283
- "Generative AI Software Infrastructure Simplified 🎉\n\n"
284
- "[![Website](https://img.shields.io/badge/Website-confidentialmind.com-blue)](https://confidentialmind.com) \n"
285
- "[![Email](https://img.shields.io/badge/Email-info%40confidentialmind.com-orange)](mailto:[email protected])\n\n"
286
- )
287
-
288
- # Title plus warning (if any)
289
- title = f"# 🔥 Quantized Model: {quantized_model_name} {chosen_emoji} 🔥\n{warning_text}\n"
290
-
291
- # Collapsible sections using <details> tags:
292
- model_details_section = f"""<details>
293
- <summary><strong>Model Details</strong></summary>
294
-
295
- - **Original Model:** [{source_model}](https://huggingface.co/{source_model})
296
- - **Quantized Model:** {quantized_model_name} (this repository)
297
- - **Quantization Method:** GPTQ (4-bit, group size {group_size_int})
298
- - **Quantization Library:** [GPTQModel](https://github.com/ModelCloud/GPTQModel/tree/main)
299
- - **Calibration Dataset:** {calibration_dataset} (using {nsamples} samples with seq len {seq_len})
300
- - **Quantized by:** [ConfidentialMind.com](https://www.confidentialmind.com)
301
- ```
302
-
303
- </details>
304
- """
305
-
306
- usage_section = f"""<details>
307
- <summary><strong>Usage</strong></summary>
308
-
309
- ```python
310
- from gptqmodel import GPTQModel
311
- from transformers import AutoTokenizer
312
-
313
- # Use the local directory or {username}/{quantized_model_name} after upload
314
- quantized_model_id = "{quantized_model_dir}" # or "{username}/{quantized_model_name}"
315
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_id)
316
- model = GPTQModel.load(quantized_model_id, device="cuda:0") # or "cpu"
317
-
318
- input_text = "This is a test prompt"
319
- inputs = tokenizer(input_text, return_tensors="pt").to("cuda:0")
320
- outputs = model.generate(**inputs)
321
- print(tokenizer.decode(outputs[0], skip_special_tokens=True))
322
- ```
323
-
324
- </details>
325
- """
326
-
327
- package_section = """<details>
328
- <summary><strong>Package Versions and Installation Instructions</strong></summary>
329
-
330
- See `pyproject.toml` for the exact UV project file. See the [GPTQModel](https://github.com/ModelCloud/GPTQModel/tree/main) repo for more details on how to install the package.
331
-
332
- Use the provided `pyproject.toml`:
333
-
334
- ```bash
335
- uv venv
336
- source venv/bin/activate
337
- uv sync
338
- ```
339
-
340
- </details>
341
- <summary><strong>Quantization Performance</strong></summary>
342
-
343
- **Average perplexity (PPL) on wikitext-2-raw-v1 dataset:** 7.89 on on wikitext-2-raw-v1 dataset
344
- <details>
345
-
346
- </details>
347
- <summary><strong>Disclaimer</strong></summary>
348
-
349
- 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.
350
- <details>
351
- </details>
352
- <summary><strong>Contact</strong></summary>
353
-
354
- For any questions or support, please visit [ConfidentialMind](https://www.confidentialmind.com) or contact us directly.
355
-
356
- [![LinkedIn](https://img.shields.io/badge/LinkedIn-ConfidentialMind-blue)](https://www.linkedin.com/company/confidentialmind/)
357
- <details>
358
- </details>
359
- """
360
-
361
- license_section = f"""<details>
362
- <summary><strong>License</strong></summary>
363
-
364
- This model inherits the license from the original model. Please refer to the original model card for more details.
365
-
366
- Original model card: `{source_model}`
367
-
368
- </details>
369
- <summary><strong>Author</strong></summary>
370
-
371
- This model was quantized by [![LinkedIn](https://img.shields.io/badge/LinkedIn-Jaro-blue)](https://www.linkedin.com/in/jaroai/)
372
- <details>
373
-
374
- </details>
375
- <summary><strong>Acknowledgements</strong></summary>
376
-
377
- Quantization performed using the GPTQModel pipeline and a big thanks to NeuralMagic for creating the calibration dataset, as well as the models original creators and/or fine-tuners.
378
- <details>
379
-
380
-
381
- **TODO:**
382
- - HELMET
383
- - Eluther evaluation harness
 
7
  authors: "JustJaro"
8
  ---
9
 
10
+ Please use the superior (tested) quant thats now been moved to ConfidentialMind org.
11
 
12
+ Cheers,
13
+ Jaro