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