Views
No views yet
ollama run huihui_ai/Qwen3.8-abliteratedtransformers library:1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4import argparse
5from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer
6import torch
7import os
8import signal
9import time
10
11def parse_args():
12 parser = argparse.ArgumentParser(
13 description="Merge LoRA weights into huihui-ai/Huihui-Qwen3.8-27B-abliterated base model and save the full model."
14 )
15 parser.add_argument(
16 "--base_model",
17 type=str,
18 default="huihui-ai/Huihui-Qwen3.8-27B-abliterated",
19 help="HuggingFace repo or local path of the base model.",
20 )
21 parser.add_argument(
22 "--dtype",
23 type=str,
24 default="bfloat16",
25 choices=["float16", "bfloat16", "float32"],
26 help="Data type for loading the base model (default: bfloat16).",
27 )
28 parser.add_argument(
29 "--device_map",
30 type=str,
31 default="auto",
32 help="Device map for model loading (e.g. 'cpu', 'auto').",
33 )
34 return parser.parse_args()
35
36def main():
37 cpu_count = os.cpu_count()
38 print(f"Number of CPU cores in the system: {cpu_count}")
39 half_cpu_count = cpu_count // 2
40 os.environ["MKL_NUM_THREADS"] = str(half_cpu_count)
41 os.environ["OMP_NUM_THREADS"] = str(half_cpu_count)
42 torch.set_num_threads(half_cpu_count)
43
44 print(f"PyTorch threads: {torch.get_num_threads()}")
45 print(f"MKL threads: {os.getenv('MKL_NUM_THREADS')}")
46 print(f"OMP threads: {os.getenv('OMP_NUM_THREADS')}")
47
48 args = parse_args()
49
50 # Load the model and tokenizer
51 print(f"Load Model {args.base_model} ... ")
52
53 torch_dtype = {
54 "float16": torch.float16,
55 "bfloat16": torch.bfloat16,
56 "float32": torch.float32,
57 }[args.dtype]
58
59 model = AutoModelForCausalLM.from_pretrained(
60 args.base_model,
61 dtype=torch_dtype,
62 device_map=args.device_map,
63 trust_remote_code=True,
64 low_cpu_mem_usage=True,
65 )
66
67 tokenizer = AutoTokenizer.from_pretrained(args.base_model, trust_remote_code=True)
68
69 messages = []
70 class CustomTextStreamer(TextStreamer):
71 def __init__(self, tokenizer, skip_prompt=True, skip_special_tokens=True):
72 super().__init__(tokenizer, skip_prompt=skip_prompt, skip_special_tokens=skip_special_tokens)
73 self.generated_text = ""
74 self.stop_flag = False
75 self.init_time = time.time() # Record initialization time
76 self.end_time = None # To store end time
77 self.first_token_time = None # To store first token generation time
78 self.think_tokens_count = 0 # To track total think tokens
79 self.token_count = 0 # To track total tokens
80
81 def on_finalized_text(self, text: str, stream_end: bool = False):
82 if self.first_token_time is None and text.strip(): # Set first token time on first non-empty text
83 self.first_token_time = time.time()
84 if stream_end:
85 self.end_time = time.time() # Record end time when streaming ends
86
87 self.generated_text += text
88 tokens = self.tokenizer.encode(text, add_special_tokens=False)
89 self.token_count += len(tokens)
90 if self.think_tokens_count == 0 and "</think>" in self.generated_text:
91 self.think_tokens_count = self.token_count
92 print(text, end="", flush=True)
93
94 if self.stop_flag:
95 raise StopIteration
96
97 def stop_generation(self):
98 self.stop_flag = True
99 self.end_time = time.time() # Record end time when generation is stopped
100
101 def get_metrics(self):
102 """Returns initialization time, first token time, first token latency, end time, total time, total tokens, and tokens per second."""
103 if self.end_time is None:
104 self.end_time = time.time() # Set end time if not already set
105 total_time = self.end_time - self.init_time # Total time from init to end
106 tokens_per_second = self.token_count / total_time if total_time > 0 else 0
107 first_token_latency = (self.first_token_time - self.init_time) if self.first_token_time is not None else None
108 metrics = {
109 "init_time": self.init_time,
110 "first_token_time": self.first_token_time,
111 "first_token_latency": first_token_latency,
112 "end_time": self.end_time,
113 "total_time": total_time, # Total time in seconds
114 "total_tokens": self.token_count,
115 "think_tokens_count": self.think_tokens_count,
116 "real_tokens_count": self.token_count - self.think_tokens_count,
117 "tokens_per_second": tokens_per_second
118 }
119 return metrics
120
121 def generate_stream(model, tokenizer, messages, enable_thinking, skip_prompt, skip_special_tokens, max_new_tokens):
122 text = tokenizer.apply_chat_template(
123 messages,
124 tokenize=False,
125 add_generation_prompt=True,
126 enable_thinking=enable_thinking
127 )
128 inputs = tokenizer(
129 text,
130 return_tensors="pt",
131 ).to(model.device)
132
133 streamer = CustomTextStreamer(tokenizer, skip_prompt=skip_prompt, skip_special_tokens=skip_special_tokens)
134
135 def signal_handler(sig, frame):
136 streamer.stop_generation()
137 print("\n[Generation stopped by user with Ctrl+C]")
138
139 signal.signal(signal.SIGINT, signal_handler)
140
141 print("Response: ", end="", flush=True)
142 try:
143 generated_ids = model.generate(
144 **inputs,
145 max_new_tokens=max_new_tokens,
146 streamer=streamer
147 )
148 del generated_ids
149 except StopIteration:
150 print("\n[Stopped by user]")
151
152 del inputs
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 skip_prompt=True
159 skip_special_tokens=True
160 enable_thinking=False
161
162 while True:
163 print(f"skip_prompt = {skip_prompt}.")
164 print(f"skip_special_tokens = {skip_special_tokens}.")
165 print(f"enable_thinking = {enable_thinking}.")
166
167 user_input = input("User: ").strip()
168 if user_input.lower() == "/exit":
169 print("Exiting chat.")
170 break
171 if user_input.lower() == "/clear":
172 messages = []
173 print("Chat history cleared. Starting a new conversation.")
174 continue
175 if user_input.lower() == "/skip_prompt":
176 skip_prompt = not skip_prompt
177 continue
178 if user_input.lower() == "/skip_special_tokens":
179 skip_special_tokens = not skip_special_tokens
180 continue
181 if user_input.lower() == "/enable_thinking":
182 enable_thinking = not enable_thinking
183 continue
184 if not user_input:
185 print("Input cannot be empty. Please enter something.")
186 continue
187
188 messages.append({"role": "user", "content": user_input})
189 response, stop_flag, metrics = generate_stream(model, tokenizer, messages, enable_thinking, skip_prompt, skip_special_tokens, 40960)
190 print("\n\nMetrics:")
191 for key, value in metrics.items():
192 print(f" {key}: {value}")
193
194 print("", flush=True)
195
196 if stop_flag:
197 continue
198 messages.append({"role": "assistant", "content": response})
199
200if __name__ == "__main__":
201 main()
202 bc1qqnkhuchxw0zqjh2ku3lu4hq45hc6gy84uk70ge