Views
No views yet
ollama run huihui_ai/qwen3-coder-abliteratedtransformers 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-Coder-30B-A3B-Instruct-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 = []
48nothink = False
49skip_prompt=True
50skip_special_tokens=True
51do_sample = True
52
53class CustomTextStreamer(TextStreamer):
54 def __init__(self, tokenizer, skip_prompt=True, skip_special_tokens=True):
55 super().__init__(tokenizer, skip_prompt=skip_prompt, skip_special_tokens=skip_special_tokens)
56 self.generated_text = ""
57 self.stop_flag = False
58 self.init_time = time.time() # Record initialization time
59 self.end_time = None # To store end time
60 self.first_token_time = None # To store first token generation time
61 self.token_count = 0 # To track total tokens
62
63 def on_finalized_text(self, text: str, stream_end: bool = False):
64 if self.first_token_time is None and text.strip(): # Set first token time on first non-empty text
65 self.first_token_time = time.time()
66 self.generated_text += text
67 # Count tokens in the generated text
68 tokens = self.tokenizer.encode(text, add_special_tokens=False)
69 self.token_count += len(tokens)
70 print(text, end="", flush=True)
71 if stream_end:
72 self.end_time = time.time() # Record end time when streaming ends
73 if self.stop_flag:
74 raise StopIteration
75
76 def stop_generation(self):
77 self.stop_flag = True
78 self.end_time = time.time() # Record end time when generation is stopped
79
80 def get_metrics(self):
81 """Returns initialization time, first token time, first token latency, end time, total time, total tokens, and tokens per second."""
82 if self.end_time is None:
83 self.end_time = time.time() # Set end time if not already set
84 total_time = self.end_time - self.init_time # Total time from init to end
85 tokens_per_second = self.token_count / total_time if total_time > 0 else 0
86 first_token_latency = (self.first_token_time - self.init_time) if self.first_token_time is not None else None
87 metrics = {
88 "init_time": self.init_time,
89 "first_token_time": self.first_token_time,
90 "first_token_latency": first_token_latency,
91 "end_time": self.end_time,
92 "total_time": total_time, # Total time in seconds
93 "total_tokens": self.token_count,
94 "tokens_per_second": tokens_per_second
95 }
96 return metrics
97
98def generate_stream(model, tokenizer, messages, nothink, skip_prompt, skip_special_tokens, do_sample, max_new_tokens):
99 input_ids = tokenizer.apply_chat_template(
100 messages,
101 tokenize=True,
102 enable_thinking = not nothink,
103 add_generation_prompt=True,
104 return_tensors="pt"
105 )
106 attention_mask = torch.ones_like(input_ids, dtype=torch.long)
107 tokens = input_ids.to(model.device)
108 attention_mask = attention_mask.to(model.device)
109
110 streamer = CustomTextStreamer(tokenizer, skip_prompt=skip_prompt, skip_special_tokens=skip_special_tokens)
111
112 def signal_handler(sig, frame):
113 streamer.stop_generation()
114 print("\n[Generation stopped by user with Ctrl+C]")
115
116 signal.signal(signal.SIGINT, signal_handler)
117
118 generate_kwargs = {}
119 if do_sample:
120 generate_kwargs = {
121 "do_sample": do_sample,
122 "max_length": max_new_tokens,
123 "temperature": 0.7,
124 "top_k": 20,
125 "top_p": 0.8,
126 "repetition_penalty": 1.2,
127 "no_repeat_ngram_size": 2
128 }
129 else:
130 generate_kwargs = {
131 "do_sample": do_sample,
132 "max_length": max_new_tokens,
133 "repetition_penalty": 1.2,
134 "no_repeat_ngram_size": 2
135 }
136
137
138 print("Response: ", end="", flush=True)
139 try:
140 generated_ids = model.generate(
141 tokens,
142 attention_mask=attention_mask,
143 #use_cache=False,
144 pad_token_id=tokenizer.pad_token_id,
145 streamer=streamer,
146 **generate_kwargs
147 )
148 del generated_ids
149 except StopIteration:
150 print("\n[Stopped by user]")
151
152 del input_ids, attention_mask
153 torch.cuda.empty_cache()
154 signal.signal(signal.SIGINT, signal.SIG_DFL)
155
156 return streamer.generated_text, streamer.stop_flag, streamer.get_metrics()
157
158# List to store activated expert indices
159activated_experts = []
160
161# Define hook function to capture gate_probs output
162def hook_fn(module, input, output):
163 # output is gate_probs, shape: [batch_size, sequence_length, num_experts]
164 gate_probs = output
165 # Compute top-1 expert indices (since only one expert is activated)
166 _, topk_indices = gate_probs.topk(8, dim=-1) # Take top-8
167 # Flatten and store activated expert indices
168 activated_experts.extend(topk_indices.squeeze(-1).view(-1).cpu().tolist())
169
170hooks = []
171for layer in model.model.layers:
172 hooks.append(layer.mlp.gate.register_forward_hook(hook_fn))
173
174while True:
175 print(f"\nnothink: {nothink}")
176 print(f"skip_prompt: {skip_prompt}")
177 print(f"skip_special_tokens: {skip_special_tokens}")
178 print(f"do_sample: {do_sample}")
179
180 user_input = input("User: ").strip()
181 if user_input.lower() == "/exit":
182 print("Exiting chat.")
183 break
184 if user_input.lower() == "/clear":
185 messages = []
186 print("Chat history cleared. Starting a new conversation.")
187 continue
188 if user_input.lower() == "/nothink":
189 nothink = not nothink
190 continue
191 if user_input.lower() == "/skip_prompt":
192 skip_prompt = not skip_prompt
193 continue
194 if user_input.lower() == "/skip_special_tokens":
195 skip_special_tokens = not skip_special_tokens
196 continue
197 if user_input.lower() == "/do_sample":
198 do_sample = not do_sample
199 continue
200 if not user_input:
201 print("Input cannot be empty. Please enter something.")
202 continue
203
204
205 messages.append({"role": "user", "content": user_input})
206 activated_experts = []
207 response, stop_flag, metrics = generate_stream(model, tokenizer, messages, nothink, skip_prompt, skip_special_tokens, do_sample, 40960)
208 print("\n\nMetrics:")
209 for key, value in metrics.items():
210 print(f" {key}: {value}")
211
212 # Count the frequency of each activated expert
213 expert_counts = Counter(activated_experts)
214
215 # Print activation statistics
216 print("\nActivated Expert Statistics:")
217 for expert_idx, count in sorted(expert_counts.items()):
218 print(f"Expert {expert_idx}: {count} times")
219
220 print("", flush=True)
221 if stop_flag:
222 continue
223 messages.append({"role": "assistant", "content": response})
224
225# Remove all hooks after inference
226for h in hooks: h.remove()
227 bc1qqnkhuchxw0zqjh2ku3lu4hq45hc6gy84uk70ge