Mungert commited on
Commit
80c0360
·
verified ·
1 Parent(s): dec1382

Upload README.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. README.md +435 -0
README.md ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ - fr
5
+ - de
6
+ - es
7
+ - pt
8
+ - it
9
+ - ja
10
+ - ko
11
+ - ru
12
+ - zh
13
+ - ar
14
+ - fa
15
+ - id
16
+ - ms
17
+ - ne
18
+ - pl
19
+ - ro
20
+ - sr
21
+ - sv
22
+ - tr
23
+ - uk
24
+ - vi
25
+ - hi
26
+ - bn
27
+ license: apache-2.0
28
+ library_name: vllm
29
+ inference: false
30
+ base_model:
31
+ - mistralai/Magistral-Small-2506
32
+ extra_gated_description: >-
33
+ If you want to learn more about how we process your personal data, please read
34
+ our <a href="https://mistral.ai/terms/">Privacy Policy</a>.
35
+ pipeline_tag: text2text-generation
36
+ tags:
37
+ - chat
38
+ - abliterated
39
+ - uncensored
40
+ extra_gated_prompt: >-
41
+ **Usage Warnings**
42
+
43
+
44
+ “**Risk of Sensitive or Controversial Outputs**“: This model’s safety filtering has been significantly reduced, potentially generating sensitive, controversial, or inappropriate content. Users should exercise caution and rigorously review generated outputs.
45
+
46
+ “**Not Suitable for All Audiences**:“ Due to limited content filtering, the model’s outputs may be inappropriate for public settings, underage users, or applications requiring high security.
47
+
48
+ “**Legal and Ethical Responsibilities**“: Users must ensure their usage complies with local laws and ethical standards. Generated content may carry legal or ethical risks, and users are solely responsible for any consequences.
49
+
50
+ “**Research and Experimental Use**“: It is recommended to use this model for research, testing, or controlled environments, avoiding direct use in production or public-facing commercial applications.
51
+
52
+ “**Monitoring and Review Recommendations**“: Users are strongly advised to monitor model outputs in real-time and conduct manual reviews when necessary to prevent the dissemination of inappropriate content.
53
+
54
+ “**No Default Safety Guarantees**“: Unlike standard models, this model has not undergone rigorous safety optimization. huihui.ai bears no responsibility for any consequences arising from its use.
55
+
56
+
57
+ ---
58
+
59
+ # <span style="color: #7FFF7F;">Magistral-Small-2506-abliterated GGUF Models</span>
60
+
61
+
62
+ ## <span style="color: #7F7FFF;">Model Generation Details</span>
63
+
64
+ This model was generated using [llama.cpp](https://github.com/ggerganov/llama.cpp) at commit [`7f4fbe51`](https://github.com/ggerganov/llama.cpp/commit/7f4fbe5183b23b6b2e25fd1ccc5d1fa8bb010cb7).
65
+
66
+
67
+
68
+
69
+
70
+ ---
71
+
72
+ ## <span style="color: #7FFF7F;">Quantization Beyond the IMatrix</span>
73
+
74
+ I've been experimenting with a new quantization approach that selectively elevates the precision of key layers beyond what the default IMatrix configuration provides.
75
+
76
+ In my testing, standard IMatrix quantization underperforms at lower bit depths, especially with Mixture of Experts (MoE) models. To address this, I'm using the `--tensor-type` option in `llama.cpp` to manually "bump" important layers to higher precision. You can see the implementation here:
77
+ 👉 [Layer bumping with llama.cpp](https://github.com/Mungert69/GGUFModelBuilder/blob/main/model-converter/tensor_list_builder.py)
78
+
79
+ While this does increase model file size, it significantly improves precision for a given quantization level.
80
+
81
+ ### **I'd love your feedback—have you tried this? How does it perform for you?**
82
+
83
+
84
+
85
+
86
+ ---
87
+
88
+ <a href="https://readyforquantum.com/huggingface_gguf_selection_guide.html" style="color: #7FFF7F;">
89
+ Click here to get info on choosing the right GGUF model format
90
+ </a>
91
+
92
+ ---
93
+
94
+
95
+
96
+ <!--Begin Original Model Card-->
97
+
98
+
99
+ # huihui-ai/Magistral-Small-2506-abliterated
100
+
101
+ This is an uncensored version of [mistralai/Magistral-Small-2506](https://huggingface.co/mistralai/Magistral-Small-2506) created with abliteration (see [remove-refusals-with-transformers](https://github.com/Sumandora/remove-refusals-with-transformers) to know more about it).
102
+ This is a crude, proof-of-concept implementation to remove refusals from an LLM model without using TransformerLens.
103
+
104
+ ## ollama
105
+
106
+ You can use [huihui_ai/magistral-abliterated](https://ollama.com/huihui_ai/magistral-abliterated) directly,
107
+ Switch the thinking toggle using /set think and /set nothink
108
+ ```
109
+ ollama run huihui_ai/magistral-abliterated
110
+ ```
111
+
112
+ ## Usage
113
+ You can use this model in your applications by loading it with Hugging Face's `transformers` library:
114
+
115
+
116
+ ```python
117
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, TextStreamer
118
+ import torch
119
+ import os
120
+ import signal
121
+ import time
122
+ import numpy as np
123
+ import random
124
+
125
+ cpu_count = os.cpu_count()
126
+ print(f"Number of CPU cores in the system: {cpu_count}")
127
+ half_cpu_count = cpu_count // 2
128
+ os.environ["MKL_NUM_THREADS"] = str(half_cpu_count)
129
+ os.environ["OMP_NUM_THREADS"] = str(half_cpu_count)
130
+ torch.set_num_threads(half_cpu_count)
131
+
132
+ print(f"PyTorch threads: {torch.get_num_threads()}")
133
+ print(f"MKL threads: {os.getenv('MKL_NUM_THREADS')}")
134
+ print(f"OMP threads: {os.getenv('OMP_NUM_THREADS')}")
135
+
136
+ # Load the model and tokenizer
137
+ NEW_MODEL_ID = "huihui-ai/Magistral-Small-2506-abliterated"
138
+ print(f"Load Model {NEW_MODEL_ID} ... ")
139
+
140
+ tokenizer = AutoTokenizer.from_pretrained(NEW_MODEL_ID, trust_remote_code=True)
141
+ #if tokenizer.pad_token is None:
142
+ # tokenizer.pad_token = tokenizer.eos_token
143
+ #tokenizer.pad_token_id = tokenizer.eos_token_id
144
+
145
+ quant_config_4 = BitsAndBytesConfig(
146
+ load_in_4bit=True,
147
+ bnb_4bit_compute_dtype=torch.bfloat16,
148
+ bnb_4bit_use_double_quant=True,
149
+ llm_int14_enable_fp32_cpu_offload=True,
150
+ )
151
+
152
+ model = AutoModelForCausalLM.from_pretrained(
153
+ NEW_MODEL_ID,
154
+ device_map="auto",
155
+ trust_remote_code=True,
156
+ quantization_config=quant_config_4,
157
+ torch_dtype=torch.bfloat16
158
+ )
159
+
160
+ def load_system_prompt(repo_id: str, filename: str) -> str:
161
+ file_path = f"{repo_id}/{filename}"
162
+ with open(file_path, "r") as file:
163
+ system_prompt = file.read()
164
+ return system_prompt
165
+
166
+ SYSTEM_PROMPT = load_system_prompt(NEW_MODEL_ID, "SYSTEM_PROMPT.txt")
167
+
168
+
169
+ initial_messages = [{"role": "system", "content": SYSTEM_PROMPT}]
170
+ messages = initial_messages.copy()
171
+ nothink = False
172
+ same_seed = False
173
+ skip_prompt=True
174
+ skip_special_tokens=True
175
+ do_sample = True
176
+
177
+ def set_random_seed(seed=None):
178
+ """Set random seed for reproducibility. If seed is None, use int(time.time())."""
179
+ if seed is None:
180
+ seed = int(time.time()) # Convert float to int
181
+ random.seed(seed)
182
+ np.random.seed(seed)
183
+ torch.manual_seed(seed)
184
+ torch.cuda.manual_seed_all(seed) # If using CUDA
185
+ torch.backends.cudnn.deterministic = True
186
+ torch.backends.cudnn.benchmark = False
187
+ return seed # Return seed for logging if needed
188
+
189
+ def apply_chat_template(tokenizer, messages, nothink, add_generation_prompt=True):
190
+ input_ids = tokenizer.apply_chat_template(
191
+ messages,
192
+ tokenize=False,
193
+ add_generation_prompt=add_generation_prompt,
194
+ )
195
+ if nothink:
196
+ input_ids += "\n<think>\n\n</think>\n"
197
+ return input_ids
198
+
199
+ class CustomTextStreamer(TextStreamer):
200
+ def __init__(self, tokenizer, skip_prompt=True, skip_special_tokens=True):
201
+ super().__init__(tokenizer, skip_prompt=skip_prompt, skip_special_tokens=skip_special_tokens)
202
+ self.generated_text = ""
203
+ self.stop_flag = False
204
+ self.init_time = time.time() # Record initialization time
205
+ self.end_time = None # To store end time
206
+ self.first_token_time = None # To store first token generation time
207
+ self.token_count = 0 # To track total tokens
208
+
209
+ def on_finalized_text(self, text: str, stream_end: bool = False):
210
+ if self.first_token_time is None and text.strip(): # Set first token time on first non-empty text
211
+ self.first_token_time = time.time()
212
+ self.generated_text += text
213
+ # Count tokens in the generated text
214
+ tokens = self.tokenizer.encode(text, add_special_tokens=False)
215
+ self.token_count += len(tokens)
216
+ print(text, end="", flush=True)
217
+ if stream_end:
218
+ self.end_time = time.time() # Record end time when streaming ends
219
+ if self.stop_flag:
220
+ raise StopIteration
221
+
222
+ def stop_generation(self):
223
+ self.stop_flag = True
224
+ self.end_time = time.time() # Record end time when generation is stopped
225
+
226
+ def get_metrics(self):
227
+ """Returns initialization time, first token time, first token latency, end time, total time, total tokens, and tokens per second."""
228
+ if self.end_time is None:
229
+ self.end_time = time.time() # Set end time if not already set
230
+ total_time = self.end_time - self.init_time # Total time from init to end
231
+ tokens_per_second = self.token_count / total_time if total_time > 0 else 0
232
+ first_token_latency = (self.first_token_time - self.init_time) if self.first_token_time is not None else None
233
+ metrics = {
234
+ "init_time": self.init_time,
235
+ "first_token_time": self.first_token_time,
236
+ "first_token_latency": first_token_latency,
237
+ "end_time": self.end_time,
238
+ "total_time": total_time, # Total time in seconds
239
+ "total_tokens": self.token_count,
240
+ "tokens_per_second": tokens_per_second
241
+ }
242
+ return metrics
243
+
244
+ def generate_stream(model, tokenizer, messages, nothink, skip_prompt, skip_special_tokens, do_sample, max_new_tokens):
245
+ formatted_prompt = apply_chat_template(tokenizer, messages, nothink)
246
+ input_ids = tokenizer(
247
+ formatted_prompt,
248
+ return_tensors="pt",
249
+ return_attention_mask=True,
250
+ padding=False
251
+ )
252
+
253
+ tokens = input_ids['input_ids'].to(model.device)
254
+ attention_mask = input_ids['attention_mask'].to(model.device)
255
+
256
+ streamer = CustomTextStreamer(tokenizer, skip_prompt=skip_prompt, skip_special_tokens=skip_special_tokens)
257
+
258
+ def signal_handler(sig, frame):
259
+ streamer.stop_generation()
260
+ print("\n[Generation stopped by user with Ctrl+C]")
261
+
262
+ signal.signal(signal.SIGINT, signal_handler)
263
+
264
+ if do_sample:
265
+ generate_kwargs = {
266
+ "do_sample": do_sample,
267
+ "max_length": max_new_tokens,
268
+ "temperature": 0.6,
269
+ "top_k": 20,
270
+ "top_p": 0.95,
271
+ "repetition_penalty": 1.2,
272
+ "no_repeat_ngram_size": 2
273
+ }
274
+ else:
275
+ generate_kwargs = {
276
+ "do_sample": do_sample,
277
+ "max_length": max_new_tokens,
278
+ "repetition_penalty": 1.2,
279
+ "no_repeat_ngram_size": 2
280
+ }
281
+
282
+ print("Response: ", end="", flush=True)
283
+ try:
284
+ generated_ids = model.generate(
285
+ tokens,
286
+ attention_mask=attention_mask,
287
+ #use_cache=False,
288
+ pad_token_id=tokenizer.pad_token_id,
289
+ streamer=streamer,
290
+ **generate_kwargs
291
+ )
292
+ del generated_ids
293
+ except StopIteration:
294
+ print("\n[Stopped by user]")
295
+
296
+ del input_ids, attention_mask
297
+ torch.cuda.empty_cache()
298
+ signal.signal(signal.SIGINT, signal.SIG_DFL)
299
+
300
+ return streamer.generated_text, streamer.stop_flag, streamer.get_metrics()
301
+
302
+ init_seed = set_random_seed()
303
+
304
+ while True:
305
+ if same_seed:
306
+ set_random_seed(init_seed)
307
+ else:
308
+ init_seed = set_random_seed()
309
+
310
+ print(f"\nnothink: {nothink}")
311
+ print(f"skip_prompt: {skip_prompt}")
312
+ print(f"skip_special_tokens: {skip_special_tokens}")
313
+ print(f"do_sample: {do_sample}")
314
+ print(f"same_seed: {same_seed}, {init_seed}\n")
315
+
316
+ user_input = input("User: ").strip()
317
+ if user_input.lower() == "/exit":
318
+ print("Exiting chat.")
319
+ break
320
+ if user_input.lower() == "/clear":
321
+ messages = initial_messages.copy()
322
+ print("Chat history cleared. Starting a new conversation.")
323
+ continue
324
+ if user_input.lower() == "/nothink":
325
+ nothink = not nothink
326
+ continue
327
+ if user_input.lower() == "/skip_prompt":
328
+ skip_prompt = not skip_prompt
329
+ continue
330
+ if user_input.lower() == "/skip_special_tokens":
331
+ skip_special_tokens = not skip_special_tokens
332
+ continue
333
+ if user_input.lower().startswith("/same_seed"):
334
+ parts = user_input.split()
335
+ if len(parts) == 1: # /same_seed (no number)
336
+ same_seed = not same_seed # Toggle switch
337
+ elif len(parts) == 2: # /same_seed <number>
338
+ try:
339
+ init_seed = int(parts[1]) # Extract and convert number to int
340
+ same_seed = True
341
+ except ValueError:
342
+ print("Error: Please provide a valid integer after /same_seed")
343
+ continue
344
+ if user_input.lower() == "/do_sample":
345
+ do_sample = not do_sample
346
+ continue
347
+ if not user_input:
348
+ print("Input cannot be empty. Please enter something.")
349
+ continue
350
+
351
+ messages.append({"role": "user", "content": user_input})
352
+ response, stop_flag, metrics = generate_stream(model, tokenizer, messages, nothink, skip_prompt, skip_special_tokens, do_sample, 40960)
353
+ print("\nMetrics:")
354
+ for key, value in metrics.items():
355
+ print(f" {key}: {value}")
356
+ print("", flush=True)
357
+ if stop_flag:
358
+ continue
359
+ messages.append({"role": "assistant", "content": response})
360
+
361
+ ```
362
+
363
+
364
+ ### Donation
365
+
366
+ If you like it, please click 'like' and follow us for more updates.
367
+ You can follow [x.com/support_huihui](https://x.com/support_huihui) to get the latest model information from huihui.ai.
368
+
369
+ If you have any questions, insights, or specific ablation models you want to request, please send an email to [email protected]
370
+
371
+ ##### Your donation helps us continue our further development and improvement, a cup of coffee can do it.
372
+ - bitcoin(BTC):
373
+ ```
374
+ bc1qqnkhuchxw0zqjh2ku3lu4hq45hc6gy84uk70ge
375
+ ```
376
+
377
+
378
+ <!--End Original Model Card-->
379
+
380
+ ---
381
+
382
+ # <span id="testllm" style="color: #7F7FFF;">🚀 If you find these models useful</span>
383
+
384
+ Help me test my **AI-Powered Free Network Monitor Assistant** with **quantum-ready security checks**:
385
+
386
+ 👉 [Free Network Monitor](https://readyforquantum.com/?assistant=open&utm_source=huggingface&utm_medium=referral&utm_campaign=huggingface_repo_readme)
387
+
388
+
389
+ The full Open Source Code for the Free Network Monitor Service available at my github repos ( repos with NetworkMonitor in the name) : [Source Code Free Network Monitor](https://github.com/Mungert69). You will also find the code I use to quantize the models if you want to do it yourself [GGUFModelBuilder](https://github.com/Mungert69/GGUFModelBuilder)
390
+
391
+ 💬 **How to test**:
392
+ Choose an **AI assistant type**:
393
+ - `TurboLLM` (GPT-4.1-mini)
394
+ - `HugLLM` (Hugginface Open-source models)
395
+ - `TestLLM` (Experimental CPU-only)
396
+
397
+ ### **What I’m Testing**
398
+ I’m pushing the limits of **small open-source models for AI network monitoring**, specifically:
399
+ - **Function calling** against live network services
400
+ - **How small can a model go** while still handling:
401
+ - Automated **Nmap security scans**
402
+ - **Quantum-readiness checks**
403
+ - **Network Monitoring tasks**
404
+
405
+ 🟡 **TestLLM** – Current experimental model (llama.cpp on 2 CPU threads on huggingface docker space):
406
+ - ✅ **Zero-configuration setup**
407
+ - ⏳ 30s load time (slow inference but **no API costs**) . No token limited as the cost is low.
408
+ - 🔧 **Help wanted!** If you’re into **edge-device AI**, let’s collaborate!
409
+
410
+ ### **Other Assistants**
411
+ 🟢 **TurboLLM** – Uses **gpt-4.1-mini** :
412
+ - **It performs very well but unfortunatly OpenAI charges per token. For this reason tokens usage is limited.
413
+ - **Create custom cmd processors to run .net code on Free Network Monitor Agents**
414
+ - **Real-time network diagnostics and monitoring**
415
+ - **Security Audits**
416
+ - **Penetration testing** (Nmap/Metasploit)
417
+
418
+ 🔵 **HugLLM** – Latest Open-source models:
419
+ - 🌐 Runs on Hugging Face Inference API. Performs pretty well using the lastest models hosted on Novita.
420
+
421
+ ### 💡 **Example commands you could test**:
422
+ 1. `"Give me info on my websites SSL certificate"`
423
+ 2. `"Check if my server is using quantum safe encyption for communication"`
424
+ 3. `"Run a comprehensive security audit on my server"`
425
+ 4. '"Create a cmd processor to .. (what ever you want)" Note you need to install a Free Network Monitor Agent to run the .net code from. This is a very flexible and powerful feature. Use with caution!
426
+
427
+ ### Final Word
428
+
429
+ I fund the servers used to create these model files, run the Free Network Monitor service, and pay for inference from Novita and OpenAI—all out of my own pocket. All the code behind the model creation and the Free Network Monitor project is [open source](https://github.com/Mungert69). Feel free to use whatever you find helpful.
430
+
431
+ If you appreciate the work, please consider [buying me a coffee](https://www.buymeacoffee.com/mahadeva) ☕. Your support helps cover service costs and allows me to raise token limits for everyone.
432
+
433
+ I'm also open to job opportunities or sponsorship.
434
+
435
+ Thank you! 😊