Views
No views yet
ollama run huihui_ai/qwen3-abliterated:4b-thinking-2507-q4_K_Mtransformers library:1from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, TextStreamer
2import torch
3import os
4import signal
5import random
6import numpy as np
7import time
8from collections import Counter
9
10cpu_count = os.cpu_count()
11print(f"Number of CPU cores in the system: {cpu_count}")
12half_cpu_count = cpu_count // 2
13os.environ["MKL_NUM_THREADS"] = str(half_cpu_count)
14os.environ["OMP_NUM_THREADS"] = str(half_cpu_count)
15torch.set_num_threads(half_cpu_count)
16
17print(f"PyTorch threads: {torch.get_num_threads()}")
18print(f"MKL threads: {os.getenv('MKL_NUM_THREADS')}")
19print(f"OMP threads: {os.getenv('OMP_NUM_THREADS')}")
20
21# Load the model and tokenizer
22NEW_MODEL_ID = "huihui-ai/Huihui-Qwen3-4B-Thinking-2507-abliterated"
23print(f"Load Model {NEW_MODEL_ID} ... ")
24quant_config_4 = BitsAndBytesConfig(
25 load_in_4bit=True,
26 bnb_4bit_compute_dtype=torch.bfloat16,
27 bnb_4bit_use_double_quant=True,
28 llm_int8_enable_fp32_cpu_offload=True,
29)
30
31model = AutoModelForCausalLM.from_pretrained(
32 NEW_MODEL_ID,
33 device_map="balanced",
34 trust_remote_code=True,
35 quantization_config=quant_config_4,
36 torch_dtype=torch.bfloat16,
37 low_cpu_mem_usage=True,
38)
39#print(model)
40#print(model.config)
41
42tokenizer = AutoTokenizer.from_pretrained(NEW_MODEL_ID, trust_remote_code=True)
43if tokenizer.pad_token is None:
44 tokenizer.pad_token = tokenizer.eos_token
45tokenizer.pad_token_id = tokenizer.eos_token_id
46
47messages = []
48skip_prompt=True
49skip_special_tokens=True
50do_sample = True
51
52class CustomTextStreamer(TextStreamer):
53 def __init__(self, tokenizer, skip_prompt=True, skip_special_tokens=True):
54 super().__init__(tokenizer, skip_prompt=skip_prompt, skip_special_tokens=skip_special_tokens)
55 self.generated_text = ""
56 self.stop_flag = False
57 self.init_time = time.time() # Record initialization time
58 self.end_time = None # To store end time
59 self.first_token_time = None # To store first token generation time
60 self.token_count = 0 # To track total tokens
61
62 def on_finalized_text(self, text: str, stream_end: bool = False):
63 if self.first_token_time is None and text.strip(): # Set first token time on first non-empty text
64 self.first_token_time = time.time()
65 self.generated_text += text
66 # Count tokens in the generated text
67 tokens = self.tokenizer.encode(text, add_special_tokens=False)
68 self.token_count += len(tokens)
69 print(text, end="", flush=True)
70 if stream_end:
71 self.end_time = time.time() # Record end time when streaming ends
72 if self.stop_flag:
73 raise StopIteration
74
75 def stop_generation(self):
76 self.stop_flag = True
77 self.end_time = time.time() # Record end time when generation is stopped
78
79 def get_metrics(self):
80 """Returns initialization time, first token time, first token latency, end time, total time, total tokens, and tokens per second."""
81 if self.end_time is None:
82 self.end_time = time.time() # Set end time if not already set
83 total_time = self.end_time - self.init_time # Total time from init to end
84 tokens_per_second = self.token_count / total_time if total_time > 0 else 0
85 first_token_latency = (self.first_token_time - self.init_time) if self.first_token_time is not None else None
86 metrics = {
87 "init_time": self.init_time,
88 "first_token_time": self.first_token_time,
89 "first_token_latency": first_token_latency,
90 "end_time": self.end_time,
91 "total_time": total_time, # Total time in seconds
92 "total_tokens": self.token_count,
93 "tokens_per_second": tokens_per_second
94 }
95 return metrics
96
97def generate_stream(model, tokenizer, messages, skip_prompt, skip_special_tokens, do_sample, max_new_tokens):
98 input_ids = tokenizer.apply_chat_template(
99 messages,
100 tokenize=True,
101 add_generation_prompt=True,
102 return_tensors="pt"
103 )
104 attention_mask = torch.ones_like(input_ids, dtype=torch.long)
105 tokens = input_ids.to(model.device)
106 attention_mask = attention_mask.to(model.device)
107
108 streamer = CustomTextStreamer(tokenizer, skip_prompt=skip_prompt, skip_special_tokens=skip_special_tokens)
109
110 def signal_handler(sig, frame):
111 streamer.stop_generation()
112 print("\n[Generation stopped by user with Ctrl+C]")
113
114 signal.signal(signal.SIGINT, signal_handler)
115
116 generate_kwargs = {}
117 if do_sample:
118 generate_kwargs = {
119 "do_sample": do_sample,
120 "max_length": max_new_tokens,
121 "temperature": 0.7,
122 "top_k": 20,
123 "top_p": 0.8,
124 "repetition_penalty": 1.2,
125 "no_repeat_ngram_size": 2
126 }
127 else:
128 generate_kwargs = {
129 "do_sample": do_sample,
130 "max_length": max_new_tokens,
131 "repetition_penalty": 1.2,
132 "no_repeat_ngram_size": 2
133 }
134
135
136 print("Response: ", end="", flush=True)
137 try:
138 generated_ids = model.generate(
139 tokens,
140 attention_mask=attention_mask,
141 #use_cache=False,
142 pad_token_id=tokenizer.pad_token_id,
143 streamer=streamer,
144 **generate_kwargs
145 )
146 del generated_ids
147 except StopIteration:
148 print("\n[Stopped by user]")
149
150 del input_ids, attention_mask
151 torch.cuda.empty_cache()
152 signal.signal(signal.SIGINT, signal.SIG_DFL)
153
154 return streamer.generated_text, streamer.stop_flag, streamer.get_metrics()
155
156while True:
157 print(f"skip_prompt: {skip_prompt}")
158 print(f"skip_special_tokens: {skip_special_tokens}")
159 print(f"do_sample: {do_sample}")
160
161 user_input = input("User: ").strip()
162 if user_input.lower() == "/exit":
163 print("Exiting chat.")
164 break
165 if user_input.lower() == "/clear":
166 messages = []
167 print("Chat history cleared. Starting a new conversation.")
168 continue
169 if user_input.lower() == "/skip_prompt":
170 skip_prompt = not skip_prompt
171 continue
172 if user_input.lower() == "/skip_special_tokens":
173 skip_special_tokens = not skip_special_tokens
174 continue
175 if user_input.lower() == "/do_sample":
176 do_sample = not do_sample
177 continue
178 if not user_input:
179 print("Input cannot be empty. Please enter something.")
180 continue
181
182
183 messages.append({"role": "user", "content": user_input})
184 activated_experts = []
185 response, stop_flag, metrics = generate_stream(model, tokenizer, messages, skip_prompt, skip_special_tokens, do_sample, 40960)
186 print("\n\nMetrics:")
187 for key, value in metrics.items():
188 print(f" {key}: {value}")
189
190 print("", flush=True)
191 if stop_flag:
192 continue
193 messages.append({"role": "assistant", "content": response})
194
195 bc1qqnkhuchxw0zqjh2ku3lu4hq45hc6gy84uk70ge